Skip to content

Commit 5546bb5

Browse files
Create Detect cycle in an undirected graph (using DFS).java
1 parent a741cea commit 5546bb5

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
private boolean dfs(int node, int parent, int vis[], ArrayList<ArrayList<Integer>>
5+
adj) {
6+
vis[node] = 1;
7+
// go to all adjacent nodes
8+
for(int adjacentNode: adj.get(node)) {
9+
if(vis[adjacentNode]==0) {
10+
if(dfs(adjacentNode, node, vis, adj) == true)
11+
return true;
12+
}
13+
// if adjacent node is visited and is not its own parent node
14+
else if(adjacentNode != parent) return true;
15+
}
16+
return false;
17+
}
18+
// Function to detect cycle in an undirected graph.
19+
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
20+
int vis[] = new int[V];
21+
for(int i = 0;i<V;i++) {
22+
if(vis[i] == 0) {
23+
if(dfs(i, -1, vis, adj) == true) return true;
24+
}
25+
}
26+
return false;
27+
}
28+
public static void main(String[] args)
29+
{
30+
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
31+
for (int i = 0; i < 4; i++) {
32+
adj.add(new ArrayList < > ());
33+
}
34+
adj.get(1).add(2);
35+
adj.get(2).add(1);
36+
adj.get(2).add(3);
37+
adj.get(3).add(2);
38+
39+
Solution obj = new Solution();
40+
boolean ans = obj.isCycle(4, adj);
41+
if (ans)
42+
System.out.println("1");
43+
else
44+
System.out.println("0");
45+
}
46+
47+
}

0 commit comments

Comments
 (0)