Skip to content

Commit bceb6db

Browse files
authored
Create 02 - DFS Approach.cpp
1 parent 0a7dfb3 commit bceb6db

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public:
3+
bool isCycleDFS(int node, int parent, unordered_map<int, bool> &visited, vector<vector<int>>& adj){
4+
visited[node] = true;
5+
6+
for(auto neighbour : adj[node]){
7+
if(!visited[neighbour]){
8+
bool cycleDetected = isCycleDFS(neighbour, node, visited, adj);
9+
if(cycleDetected) return true;
10+
}else if(neighbour != parent) return true;
11+
}
12+
13+
return false;
14+
}
15+
16+
bool isCycle(vector<vector<int>>& adj) {
17+
int n = adj.size();
18+
19+
unordered_map<int, bool> visited;
20+
for(int i = 0; i < n; i++){
21+
if(!visited[i]){
22+
bool ans = isCycleDFS(i, -1, visited, adj);
23+
if(ans == 1) return true;
24+
}
25+
}
26+
27+
28+
return false;
29+
}
30+
};

0 commit comments

Comments
 (0)