-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetectcycle_undirect_bfs
More file actions
28 lines (28 loc) · 940 Bytes
/
detectcycle_undirect_bfs
File metadata and controls
28 lines (28 loc) · 940 Bytes
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
bool bfshelper(int root,vector<int> adj[],vector<bool>& visited)
{
visited[root]=true;
queue<pair<int,int>> pendingnodes;
pendingnodes.push(make_pair(root,-1));
while(!pendingnodes.empty())
{
pair<int,int> front=pendingnodes.front();
pendingnodes.pop();
for(int i=0;i<adj[front.first].size();i++)
{
int neighbour=adj[front.first][i];
if(front.second==neighbour) continue;
if(visited[neighbour]) return true;
visited[neighbour]=true;
pendingnodes.push(make_pair(neighbour,front.first));
}
}
return false;
}
bool isCycle(int V, vector<int> adj[]) {
vector<bool> visited(V,false);
for(int i=0;i<V;i++)
{
if(!visited[i] && bfshelper(i,adj,visited)) return true;
}
return false;
}