-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdfs_stack_test.c
51 lines (36 loc) · 880 Bytes
/
dfs_stack_test.c
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
#include <stdio.h>
#define MAX 1000
int mat[MAX][MAX];
int visited[MAX];
int parent[MAX];
int num;
void DFS(int startnode)
{
int k;
printf("Node is [%d]\n", startnode);
for(k=0; k < num; k++){
if (mat[startnode][k] !=0 && visited[k] ==0) {
visited[k] = 1;
parent[k] = startnode;
DFS(k);
} else if (mat[startnode][k] !=0 && visited[k] == 1 && parent[startnode] != k) {
printf("Cycle is detected...startnode[%d] ancestor [%d]\n", startnode, k);
return;
}
}
}
int main(void)
{
int r, c, k;
printf("Welcome to DFS traversal..\n");
printf("Enter number of nodes..\n");
scanf("%d", &num);
for(r=0; r< num; r++) {
for (c=0; c<num; c++) {
scanf("%d", &mat[r][c]);
}
}
visited[2] = 1;
parent[2] = 2;
DFS(2);
}