Skip to content

Commit 8bb6332

Browse files
authored
Create 01 - DFS Approach.cpp
1 parent e36ff61 commit 8bb6332

File tree

1 file changed

+31
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)