Skip to content

Commit 545b67d

Browse files
committed
detects cycle in undirected Graph
1 parent 9a120e1 commit 545b67d

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package Graph;
2+
3+
import java.util.ArrayList;
4+
5+
public class DetectCycleUndirectedGraph {
6+
7+
private static boolean hasCycle(ArrayList<ArrayList<Integer>> adjList) {
8+
return depthFirstTraverse(adjList);
9+
}
10+
11+
private static boolean depthFirstTraverse(ArrayList<ArrayList<Integer>> adjList) {
12+
13+
boolean[] visited = new boolean[adjList.size()];
14+
15+
for (int i = 0; i < adjList.size(); i++) {
16+
17+
if (visited[i] == false) {
18+
19+
int isParent = -1;
20+
if (dfsRecursion(adjList, i, visited, isParent) == true) {
21+
return true;
22+
}
23+
}
24+
}
25+
return false;
26+
}
27+
28+
private static boolean dfsRecursion(ArrayList<ArrayList<Integer>> adjList, int src, boolean[] visited, int parent) {
29+
visited[src] = true;
30+
31+
for (Integer neighbor : adjList.get(src)) {
32+
33+
if (visited[neighbor] == false) {
34+
35+
if (dfsRecursion(adjList, neighbor, visited, src) == true) {
36+
return true; // cycle exists
37+
}
38+
} else if (neighbor != parent)
39+
return true;
40+
}
41+
return false;
42+
}
43+
44+
public static void main(String[] args) {
45+
46+
// int totalVertices = 6; // test graph 1
47+
// int totalVertices = 5; // test graph 2
48+
int totalVertices = 4; // test graph 3
49+
50+
ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>(totalVertices);
51+
for (int i = 0; i < totalVertices; i++) {
52+
adjList.add(new ArrayList<Integer>());
53+
}
54+
55+
// test graph 1, cycle - true
56+
57+
// addEdge(adjList, 0, 1);
58+
// addEdge(adjList, 1, 2);
59+
// addEdge(adjList, 1, 3);
60+
// addEdge(adjList, 3, 2);
61+
// addEdge(adjList, 2, 4);
62+
// addEdge(adjList, 4, 5);
63+
64+
// test graph 2, cycle - false
65+
66+
// addEdge(adjList, 0, 1);
67+
// addEdge(adjList, 1, 2);
68+
// addEdge(adjList, 1, 4);
69+
// addEdge(adjList, 2, 3);
70+
71+
// test graph 3, cycle - true
72+
73+
addEdge(adjList, 0, 1);
74+
addEdge(adjList, 0, 3);
75+
addEdge(adjList, 1, 3);
76+
addEdge(adjList, 1, 2);
77+
addEdge(adjList, 2, 3);
78+
79+
System.out.println("adjacency list representation of Graph\n");
80+
display(adjList);
81+
82+
System.out.println("\nhas cycle: " + hasCycle(adjList)); // 2
83+
}
84+
85+
private static void addEdge(ArrayList<ArrayList<Integer>> adjList, int u, int v) {
86+
adjList.get(u).add(v);
87+
adjList.get(v).add(u);
88+
}
89+
90+
public static void display(ArrayList<ArrayList<Integer>> adjList) {
91+
for (int i = 0; i < adjList.size(); i++) {
92+
System.out.println(i + ": " + adjList.get(i));
93+
}
94+
}
95+
}

0 commit comments

Comments
Β (0)