-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphIntro14.cpp
More file actions
71 lines (56 loc) · 1.28 KB
/
GraphIntro14.cpp
File metadata and controls
71 lines (56 loc) · 1.28 KB
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
//Cycle Detection in directed Graph
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/* Function to check if the given graph contains cycle
* V: number of vertices
* adj[]: representation of graph
*/
bool isCyclic_util(vector<int> adj[], vector<bool> visited, int curr)
{
if (visited[curr] == true)
return true;
visited[curr] = true;
bool FLAG = false;
for (int i = 0; i < adj[curr].size(); ++i)
{
FLAG = isCyclic_util(adj, visited, adj[curr][i]);
if (FLAG == true)
return true;
}
return false;
}
bool isCyclic(int V, vector<int> adj[])
{
vector<bool> visited(V, false);
bool FLAG = false;
for (int i = 0; i < V; ++i)
{
visited[i] = true;
for (int j = 0; j < adj[i].size(); ++j)
{
FLAG = isCyclic_util(adj, visited, adj[i][j]);
if (FLAG == true)
return true;
}
visited[i] = false;
}
return false;
}
// { Driver Code Starts.
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;
} // } Driver Code Ends