-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03.CycleDetection_Undirected_DFS.java
63 lines (50 loc) · 1.61 KB
/
03.CycleDetection_Undirected_DFS.java
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
import java.util.*;
class Solution {
// Function to detect cycle in an undirected graph using DFS.
private boolean isCycle_DFS(int v, int parent, ArrayList<ArrayList<Integer>> adj, boolean[] visited) {
visited[v] = true;
for (Integer i : adj.get(v)) {
if (!visited[i]) {
if (isCycle_DFS(i, v, adj, visited)) {
return true;
}
} else if (i != parent) { // we are at a node which is visited but not parent so its cycle
return true;
}
}
return false;
}
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
boolean[] visited = new boolean[V];
Arrays.fill(visited, false);
for (int i = 0; i < V; i++) {
if (!visited[i]) {
if (isCycle_DFS(i, -1, adj, visited)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
int V = 4;
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
adj.get(0).add(1);
adj.get(1).add(0);
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(2).add(3);
adj.get(3).add(2);
adj.get(3).add(0);
adj.get(0).add(3);
if (sol.isCycle(V, adj)) {
System.out.println("Graph contains cycle");
} else {
System.out.println("Graph doesn't contain cycle");
}
}
}