Skip to content

Commit a0fe943

Browse files
authored
Create Detect Cycle in an Undirected Graph (using DFS)
1 parent 46ed601 commit a0fe943

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution {
5+
private:
6+
bool dfs(int node, int parent, int vis[], vector<int> adj[]) {
7+
vis[node] = 1;
8+
// visit adjacent nodes
9+
for(auto adjacentNode: adj[node]) {
10+
// unvisited adjacent node
11+
if(!vis[adjacentNode]) {
12+
if(dfs(adjacentNode, node, vis, adj) == true)
13+
return true;
14+
}
15+
// visited node but not a parent node
16+
else if(adjacentNode != parent) return true;
17+
}
18+
return false;
19+
}
20+
public:
21+
// Function to detect cycle in an undirected graph.
22+
bool isCycle(int V, vector<int> adj[]) {
23+
int vis[V] = {0};
24+
// for graph with connected components
25+
for(int i = 0;i<V;i++) {
26+
if(!vis[i]) {
27+
if(dfs(i, -1, vis, adj) == true) return true;
28+
}
29+
}
30+
return false;
31+
}
32+
};
33+
34+
int main() {
35+
36+
// V = 4, E = 2
37+
vector<int> adj[4] = {{}, {2}, {1, 3}, {2}};
38+
Solution obj;
39+
bool ans = obj.isCycle(4, adj);
40+
if (ans)
41+
cout << "1\n";
42+
else
43+
cout << "0\n";
44+
return 0;
45+
}

0 commit comments

Comments
 (0)