-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDetectCycleUnDirected.java
More file actions
31 lines (26 loc) · 909 Bytes
/
DetectCycleUnDirected.java
File metadata and controls
31 lines (26 loc) · 909 Bytes
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
package graph;
import java.util.ArrayList;
public class DetectCycleUnDirected {
// Time Complexity - O(V + E)
public static boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
boolean[] isVisited = new boolean[V];
for (int i = 0; i < V; i++) {
if (!isVisited[i] && cycle(adj, i, isVisited, -1)) {
return true;
}
}
return false;
}
public static boolean cycle(ArrayList<ArrayList<Integer>> adj, int curr, boolean[] isVisited, int parent) {
isVisited[curr] = true;
ArrayList<Integer> neighbours = adj.get(curr);
for (int dest : neighbours) {
if (isVisited[dest] && dest != parent) {
return true;
} else if (!isVisited[dest] && cycle(adj, dest, isVisited, curr)) {
return true;
}
}
return false;
}
}