forked from sureshmangs/Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcycle_detection_directed_graph_dfs.cpp
97 lines (75 loc) · 2.25 KB
/
cycle_detection_directed_graph_dfs.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Given a Directed Graph. Check whether it contains any cycle or not.
Input: The first line of the input contains an integer 'T' denoting the number of test cases.
Then 'T' test cases follow. Each test case consists of two lines.
Description of testcases is as follows: The First line of each test case contains two integers 'N' and 'M'
which denotes the no of vertices and no of edges respectively. The Second line of each test case contains 'M'
space separated pairs u and v denoting that there is an uni-directed edge from u to v .
Output:
The method should return 1 if there is a cycle else it should return 0.
User task:
You don't need to read input or print anything. Your task is to complete the function isCyclic which takes
the Graph and the number of vertices and inputs and returns true if the given directed graph contains a cycle. Else, it returns false.
Expected Time Complexity: O(V + E).
Expected Auxiliary Space: O(V).
Constraints:
1 <= T <= 1000
1<= N,M <= 1000
0 <= u,v <= N-1
Example:
Input:
3
2 2
0 1 0 0
4 3
0 1 1 2 2 3
4 3
0 1 2 3 3 2
Output:
1
0
1
Explanation:
Testcase 1: In the above graph there are 2 vertices. The edges are as such among the vertices.
From graph it is clear that it contains cycle.
*/
#include <bits/stdc++.h>
using namespace std;
bool dfs(int s, vector<int> adj[], vector <bool> &vis, vector <bool> &dfsVis) {
vis[s] = true;
dfsVis[s] = true;
for (auto &x: adj[s]) {
if (!vis[x]) {
if (dfs(x, adj, vis, dfsVis)) return true;
} else if (dfsVis[x]) {
return true; // cycle exist
}
}
dfsVis[s] = false;
return false; // cycle doesn't exist
}
bool isCyclic(int V, vector<int> adj[]) {
vector <bool> vis(V), dfsVis(V);
for (int i = 0; i < V; i++) {
if (!vis[i]) {
if (dfs(i, adj, vis, dfsVis)) return true; // cycle exist
}
}
return false; // cycle doesn't exist
}
int main() {
int t;
cin >> t;
while(t--){
int v, e;
cin >> v >> e;
vector<int> adj[v];
for(int i =0;i<e;i++){
int u, v;
cin >> u >> v;
adj[u].push_back(v);
}
cout << isCyclic(v, adj) << endl;
}
return 0;
}