-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphIntro15.cpp
More file actions
79 lines (67 loc) · 1.67 KB
/
GraphIntro15.cpp
File metadata and controls
79 lines (67 loc) · 1.67 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
72
73
74
75
76
77
78
79
//Cycle Detection In Unidirected Graph Graph Coloring Approach
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
/* This function is used to detect a cycle in undirected graph
* adj[]: array of vectors to represent graph
* V: number of vertices
*/
bool isCyclic_util(vector<int> adj[], vector<int> visited, int curr)
{
if (visited[curr] == 2)
return true;
visited[curr] = 1;
bool FLAG = false;
for (int i = 0; i < adj[curr].size(); ++i)
{
if (visited[adj[curr][i]] == 1)
visited[adj[curr][i]] = 2;
else
{
FLAG = isCyclic_util(adj, visited, adj[curr][i]);
if (FLAG == true)
return true;
}
}
return false;
}
bool isCyclic(vector<int> adj[], int V)
{
vector<int> visited(V, 0);
bool FLAG = false;
for (int i = 0; i < V; ++i)
{
visited[i] = 1;
for (int j = 0; j < adj[i].size(); ++j)
{
FLAG = isCyclic_util(adj, visited, adj[i][j]);
if (FLAG == true)
return true;
}
visited[i] = 0;
}
return false;
}
// { Driver Code Starts.
int main()
{
int T;
cin >> T;
while (T--)
{
int V, E;
cin >> V >> E;
// array of vectors to represent graph
vector<int> adj[V];
int u, v;
for (int i = 0; i < E; i++)
{
cin >> u >> v;
// adding edge to the graph
adj[u].push_back(v);
adj[v].push_back(u);
}
cout << isCyclic(adj, V) << endl;
}
}
// } Driver Code Ends