-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcycledetectionDFS.cpp
More file actions
42 lines (28 loc) · 989 Bytes
/
Copy pathcycledetectionDFS.cpp
File metadata and controls
42 lines (28 loc) · 989 Bytes
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
// Given a Directed Graph with V vertices and E edges, check whether it contains any cycle or not.
class Solution {
public:
bool isCyclicHelper(int node, vector<int> adj[], unordered_map<int,bool> &visited, unordered_map<int,bool> &instack)
{
if(visited[node]==false)
{
visited[node] = true;
instack[node] = true;
for(auto i:adj[node])
{
if(!visited[i] && isCyclicHelper(i, adj, visited, instack)) return true;
else if(instack[i]==true) return true;
}
}
instack[node] = false;
return false;
}
bool isCyclic(int V, vector<int> adj[])
{
unordered_map<int, bool> visited;
unordered_map<int, bool> instack;
for(int i=0;i<V;i++)
{
if(isCyclicHelper(i, adj, visited, instack)) return true;
}
return false;
}