-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetectcycledirectedgraph2.cpp
More file actions
65 lines (57 loc) · 1006 Bytes
/
detectcycledirectedgraph2.cpp
File metadata and controls
65 lines (57 loc) · 1006 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
using namespace std;
map<int,bool>recStack;
map<int,bool>visited;
map<int,list<int>>adj;
void addEdge(int u,int v)
{
adj[u].push_back(v);
}
bool dfs(int v)
{
if(visited[v] == false)
{
visited[v] = true;
recStack[v] = true;
list<int>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();i++)
{
if((visited[*i] == false) && dfs(*i))
{
return true;
}
else if(recStack[*i])
{
return true;
}
}
}
recStack[v] = false;
return false;
}
bool isCyclic(int V)
{
for(int i=0;i<V;i++)
{
recStack[i] = false;
visited[i] = false;
}
for(int i=0;i<V;i++)
{
if(dfs(i))
{
return true;
}
}
return false;
}
int main()
{
addEdge(1,2);
addEdge(2,3);
addEdge(3,4);
addEdge(4,2
);
addEdge(4,5);
cout<<isCyclic(5);
}