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