-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDetect_Cycle_DFS.cpp
More file actions
70 lines (67 loc) · 1.44 KB
/
Copy pathDetect_Cycle_DFS.cpp
File metadata and controls
70 lines (67 loc) · 1.44 KB
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
#include<bits/stdc++.h>
using namespace std;
class graph
{
int V;
list<int>*adj;
public:
graph(int V)
{
this->V = V;
this->adj = new list<int>[this->V];
}
void addedge(int u,int v,bool directed=false)
{
this->adj[u].push_back(v);
if(directed==false)
{
this->adj[v].push_back(u);
}
}
bool cycle_helper(vector<bool>&visited,int source,int parent)
{
visited[source] = true;
for(auto itr=this->adj[source].begin();itr!=this->adj[source].end();itr++)
{
//if neighbor not visited ,call dfs again
if(!visited[*itr])
{
bool res = cycle_helper(visited,*itr,source);
if(res)
{
return true;
}
}
//neighbor is visited but it should be a parent
else if(*itr!=parent)
{
return true;
}
}
return false;
}
bool contains_cycle()
{
vector<bool>visited(this->V,false);
return cycle_helper(visited,0,-1);
}
};
int main()
{
graph g(6);
g.addedge(0,1);
g.addedge(1,2);
g.addedge(1,3);
g.addedge(2,3);
g.addedge(2,4);
g.addedge(4,5);
if(g.contains_cycle())
{
cout<<"Graph contains_cycle\n";
}
else
{
cout<<"Graph not contains_cycle\n";
}
return 0;
}