-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDetect_Cycle_BFS.cpp
More file actions
73 lines (68 loc) · 1.49 KB
/
Detect_Cycle_BFS.cpp
File metadata and controls
73 lines (68 loc) · 1.49 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
71
72
73
#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 contains_cycle(int source)
{
vector<bool>visited(this->V,false);
vector<int> parent(this->V);
list<int>q;
q.push_back(source);
visited[source] = true;
parent[source]=source;
while(!q.empty())
{
source = q.front();
q.pop_front();
for(auto itr=this->adj[source].begin();itr!=this->adj[source].end();itr++)
{
if(visited[*itr]==true && parent[source]!=*itr)
{
return true;
}
else if(!visited[*itr])
{
visited[*itr]=true;
parent[*itr]=source;
q.push_back(*itr);
}
}
}
return false;
}
};
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(0))
{
cout<<"Graph contains_cycle\n";
}
else
{
cout<<"Graph not contains_cycle\n";
}
return 0;
}