-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleDetectionUndirBFS.cpp
More file actions
52 lines (41 loc) · 1.07 KB
/
Copy pathCycleDetectionUndirBFS.cpp
File metadata and controls
52 lines (41 loc) · 1.07 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
/* Given an undirected graph with V vertices and E edges,
check whether it contains any cycle or not using BFS
*/
class Solution {
public:
bool isCycleUtil(int V,int s, vector<int>adj[], unordered_map<int,int> &visited)
{
vector<int> parent(V,-1);
queue<int> q;
visited[s] = true;
q.push(s);
while(!q.empty())
{
int temp = q.front();
q.pop();
for(auto i:adj[temp])
{
if(!visited[i])
{
visited[i] = true;
q.push(i);
parent[i] = temp;
}
else if (parent[temp]!=i) return true;
}
}
return false;
}
bool isCycle(int V, vector<int>adj[])
{
unordered_map<int, int> visited;
for(int i=0;i<V;i++)
{
if(!visited[i])
{
if(isCycleUtil(V,i,adj,visited)) return true;
}
}
return false;
}
};