-
Notifications
You must be signed in to change notification settings - Fork 0
/
DetectCylce.cpp
41 lines (37 loc) · 1.15 KB
/
DetectCylce.cpp
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
class Solution {
public:
bool bfs(int src , vector<int> adj[], int vis[]) {
queue<pair<int, int>>q;
q.push({src,-1});
vis[src]=1;
while(!q.empty()) {
int node =q.front().first;
int parent=q.front().second;
q.pop();
for(int it : adj[node]) {
if(!vis[it]) {
q.push({it , node});
vis[it]=1;
}
//if it is visited there is two possibilites
// either it is a parent or someone else has alread visited it
else if(parent!=it) {
// this means that you are trying to visit a node
// that has been visited alrready that is not Your parent
return true;
}
}
}
return false;
}
bool isCycle(int V, vector<int> adj[]) {
// Code here
int vis[V] = {0};
for(int i=0;i<V;i++) {
if(!vis[i]) {
if(bfs(i , adj , vis))return true;
}
}
return false;
}
};