-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathCycle in a Directed Graph.cpp
47 lines (47 loc) · 1.15 KB
/
Cycle in a Directed Graph.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
42
43
44
45
46
47
// Finds a cycle starting from a node u
const int N = 1005;
bool visited[N], instack[N];
stack<int> st;
vi graph[N]; int n;
vpii cycle; // contains the edges of the cycle
bool findCycle(int u)
{
if(!visited[u])
{
visited[u]=true;
instack[u]=true;
st.push(u);
for(auto v: graph[u])
{
if(!visited[v] && findCycle(v)) return true;
else if(instack[v])
{
cycle.pb({u,v});
st.pop();
int t=u;
while(v!=t)
{
cycle.pb({st.top(),t});
t=st.top();
st.pop();
}
return true;
}
}
}
instack[u]=false;
st.pop();
return false;
}
void find()
{
FOR(i,1,n+1)
{
ms(visited,false);
ms(instack,false);
if(findCycle(i))
{
// A cycle found starting from i
}
}
}