-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcycle_in_directed_geek.c
76 lines (61 loc) · 1.39 KB
/
cycle_in_directed_geek.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <stdio.h>
#define MAX 1000
#define INF 99999
int graph[MAX][MAX];
int num;
int parent[MAX];
int visited[MAX];
void PrintCycle(int startnode, int cyclestart)
{
while(parent[
}
int DFS(int startnode)
{
int adj;
for(adj=0; adj < num; adj++) {
if (graph[startnode][adj] == INF)
continue;
if (!visited[adj]) {
printf("Adjacent node [%d], parent[%d] \n", adj, startnode);
visited[adj] = 1;
parent[adj] = startnode;
if (DFS(adj) == -1)
return -1;
} else if (visited[adj]) {
/* Found a cycle */
printf("Found a cycle.. startnode %d adj %d\n", startnode, adj);
PrintCycle(startnode, adj);
return -1;
}
}
return 1;
}
int main()
{
int r;
int c;
int k;
int result;
printf("Welcome to find Cycle in Directed graph..\n");
printf("Enter number of nodes..\n");
scanf("%d", &num);
for(r=0; r< num; r++) {
for(c=0; c< num; c++) {
scanf("%d", &graph[r][c]);
}
}
for(k=0; k< num; k++) {
visited[k] = 0;
parent[k] = -1;
}
for (k=0; k < num; k++) {
if (visited[k] == 0) {
visited[k] = 1;
int result = DFS(k);
printf("Result [%d]\n", result);
}
if(result)
continue;
}
}
}