Skip to content

Commit 12a5046

Browse files
committed
Detect Cycle in a directed graph
1 parent 46a10a0 commit 12a5046

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
5+
6+
7+
/* Function to check if the given graph contains cycle
8+
* V: number of vertices
9+
* adj[]: representation of graph
10+
*/
11+
bool check_cycle(vector<int> g[],int *visit,int *cycle,int k){
12+
cycle[k] = 1;
13+
visit[k] = 1;
14+
15+
for(auto i = g[k].begin();i!=g[k].end();i++){
16+
if(cycle[*i] == 1){
17+
return true;
18+
}
19+
20+
else if(cycle[*i] == 0)
21+
if(visit[*i] != 0 && check_cycle(g,visit,cycle,*i))return true;
22+
23+
}
24+
cycle[k] = 0;
25+
return false;
26+
}
27+
28+
29+
bool isCyclic(int V, vector<int> adj[])
30+
{
31+
int visited[V] = {0};
32+
int cycleCheck[V] = {0};
33+
for(int i=0;i<V;i++){
34+
if(visited[i] == 0){
35+
if(check_cycle(adj,visited,cycleCheck,i))
36+
return true;
37+
}
38+
}
39+
return false;
40+
41+
}
42+
43+
44+
45+
46+
int main() {
47+
48+
int t;
49+
cin >> t;
50+
51+
while(t--){
52+
53+
int v, e;
54+
cin >> v >> e;
55+
56+
vector<int> adj[v];
57+
58+
for(int i =0;i<e;i++){
59+
int u, v;
60+
cin >> u >> v;
61+
adj[u].push_back(v);
62+
}
63+
64+
cout << isCyclic(v, adj) << endl;
65+
66+
}
67+
68+
return 0;
69+
}

0 commit comments

Comments
 (0)