-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle detection using dfs.c++
102 lines (81 loc) · 1.46 KB
/
cycle detection using dfs.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<iostream>
#include<cstdlib>
#include<stack>
#include<conio.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
typedef struct node node;
node *g[5];
node * create(int d)
{
node *t=(node *)malloc(sizeof(node));
t->data=d;
t->next=NULL;
return t;
}
bool visited[5]={false,false,false,false,false};
int cycle(int vertex,int parent)
{
visited[vertex]=true;
node *i=g[vertex];
while(i!=NULL)
{
if(visited[i->data]==false)
{
if(cycle(i->data,vertex) )
return 1;
}
else if(i->data!=parent)
return 1;
i=i->next;
}
return 0;
}
void dfs(node *g[],int v)
{
int i,f=0;
for(i=0;i<v;i++)
{
if(visited[i]==false )
if(cycle(i,-1))
{cout<<"Cycle present";
f=1;
break;
}
}
if(f==0)
cout<<"cycle not present";
}
int main()
{
int i;
g[0]=create(1);
g[0]->next=create(2);
g[1]=create(0);
g[2]=create(0);
g[2]->next=create(3);
g[2]->next->next=create(4);
g[3]=create(4);
g[3]->next=create(2);
g[4]=create(3);
g[4]->next=create(2);
for(i=0;i<5;i++)
{
node *t=g[i];
cout<<"Node="<<i<<"=";
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<"\n";
}
cout<<"\n";
dfs(g,5);
getch();
return 0;
}