Skip to content

Commit 46ed601

Browse files
authored
Create Detect cycle in an undirected graph GFG
1 parent 4f6fb61 commit 46ed601

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution {
5+
private:
6+
bool detect(int src, vector<int> adj[], int vis[]) {
7+
vis[src] = 1;
8+
// store <source node, parent node>
9+
queue<pair<int,int>> q;
10+
q.push({src, -1});
11+
// traverse until queue is not empty
12+
while(!q.empty()) {
13+
int node = q.front().first;
14+
int parent = q.front().second;
15+
q.pop();
16+
17+
// go to all adjacent nodes
18+
for(auto adjacentNode: adj[node]) {
19+
// if adjacent node is unvisited
20+
if(!vis[adjacentNode]) {
21+
vis[adjacentNode] = 1;
22+
q.push({adjacentNode, node});
23+
}
24+
// if adjacent node is visited and is not it's own parent node
25+
else if(parent != adjacentNode) {
26+
// yes it is a cycle
27+
return true;
28+
}
29+
}
30+
}
31+
// there's no cycle
32+
return false;
33+
}
34+
public:
35+
// Function to detect cycle in an undirected graph.
36+
bool isCycle(int V, vector<int> adj[]) {
37+
// initialise them as unvisited
38+
int vis[V] = {0};
39+
for(int i = 0;i<V;i++) {
40+
if(!vis[i]) {
41+
if(detect(i, adj, vis)) return true;
42+
}
43+
}
44+
return false;
45+
}
46+
};
47+
48+
int main() {
49+
50+
// V = 4, E = 2
51+
vector<int> adj[4] = {{}, {2}, {1, 3}, {2}};
52+
Solution obj;
53+
bool ans = obj.isCycle(4, adj);
54+
if (ans)
55+
cout << "1\n";
56+
else
57+
cout << "0\n";
58+
return 0;
59+
}

0 commit comments

Comments
 (0)