Skip to content

Commit 0a7dfb3

Browse files
authored
Create 01 - BFS Approach.cpp
1 parent c0e6c61 commit 0a7dfb3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public:
3+
bool isCycleBFS(int src, unordered_map<int, bool> &visited, vector<vector<int>>& adj){
4+
unordered_map<int, int> parent;
5+
6+
parent[src] = -1;
7+
visited[src] = true;
8+
queue<int> q;
9+
q.push(src);
10+
11+
while(!q.empty()){
12+
int front = q.front();
13+
q.pop();
14+
15+
for(auto neighbour : adj[front]){
16+
if(visited[neighbour] == true && neighbour != parent[front]) return true;
17+
else if(!visited[neighbour]){
18+
q.push(neighbour);
19+
visited[neighbour] = true;
20+
parent[neighbour] = front;
21+
}
22+
}
23+
}
24+
25+
return false;
26+
}
27+
28+
bool isCycle(vector<vector<int>>& adj) {
29+
int n = adj.size();
30+
31+
unordered_map<int, bool> visited;
32+
for(int i = 0; i < n; i++){
33+
if(!visited[i]){
34+
bool ans = isCycleBFS(i, visited, adj);
35+
if(ans == 1) return true;
36+
}
37+
}
38+
39+
40+
return false;
41+
}
42+
};

0 commit comments

Comments
 (0)