Adjacency matrix of a cycle graph

Please kindly identify my error in this code. It is not giving the required output and prescribed by the question:
Cycles
Is a graph denoted by the adjacency matrix a cycle graph?

Input
In the first line: a number of next lines.
In a line (expect the first): a number of vertices and after space an adjacency matrix written from the left to the right and from the top to the bottom.

Output
1 if a graph is a cycle, 0 else.
Example

Input
5
3 011101110
7 0110000101000011000000000101000101000001010001010
7 0100001101000001010000010100000101000001011000010
5 0101010000000011000000100
5 0100110010000110110010100

Output
1
0
1
0
1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
using namespace std;

char matrix[100][100];

int main()
{
	
	int n,i,j;
	cin>>n;
	for(i=0;i<n;i++){
		for(j=0;j<n;j++) {
		    cin>>matrix[j][i];       
		}
	}
	
	
	int cycle = 1;
	
	for(i = 0; i<n && cycle == 1;i++) {
	    for(j = 0; j<n && cycle == 1; j++) {
	         if(i == j) {
	            if(matrix[i][j] == '1') {
	                cycle = 0;
	                break;
	            }
	         }
	         if(matrix[i][j] == '1' && matrix[j][i] != '1') {
	            cycle = 0;
	            break;
	         }
	         
	                  
	    }
	}
	
	
	cout<<cycle;
	
	
	return 0;
	
/* 	011
// 	101
	110
	
	
	0110000
	1010000
	1100000
	0000101
	0001010
	0000101
	0001010
	
	0100001
	1010000
	0101000
	0010100
	0001010
	0000101
	1000010
*/	
	
}
Last edited on
I haven't tried too hard to trace through your code, but it looks like you do not have a “visited” flag — you appear to be trying to reuse the edge value for that... which won’t work.

The simplest solution for your code would be to simply keep an additional array of “nodes visited”:

1
2
bool graph[100][100];  // Directed graph as an adjacency matrix
bool visited[100];     // Was node visited? 

Now you should be looking at a DFS to run through the graph, making sure to set a node as visited when you encounter it and to clear the node as unvisited when you are back-tracking.

Remember, this is a recursive algorithm! You need a FUNCTION.
(You could certainly write it iteratively, but don’t.)

Hope this helps.
Topic archived. No new replies allowed.