- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathcycleDetectionInDirectedGraph.java
31 lines (28 loc) · 1 KB
/
cycleDetectionInDirectedGraph.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
importjava.util.ArrayList;
// check whether the graph is DAG, directed acyclic(without cycles) graph
publicclasscycleDetectionInDirectedGraph {
privatebooleancheckCycle(intnode, ArrayList<ArrayList<Integer>> adj, int[] visited, intdfsVisited[]) {
visited[node] = 1;
dfsVisited[node] = 1;
for (Integerchild : adj.get(node)) {
if (visited[child] == 0) {
if (checkCycle(child, adj, visited, dfsVisited))
returntrue;
} elseif (dfsVisited[child] == 1)
returntrue;
}
returnfalse;
}
publicbooleanisCyclic(intN, ArrayList<ArrayList<Integer>> adjlist, intn) {
intvisited[] = newint[N];
intdfsVisited[] = newint[N];
for (inti = 0; i < n; i++) {
if (visited[i] == 0) {
if (checkCycle(i, adjlist, visited, dfsVisited) == true) {
returntrue;
}
}
}
returnfalse;
}
}