- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathDetectCycleDirectedGraph.java
88 lines (64 loc) Β· 2.16 KB
/
DetectCycleDirectedGraph.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
packageGraph;
importjava.util.ArrayList;
publicclassDetectCycleDirectedGraph {
publicstaticvoidmain(String[] args) {
inttotalVertices = 4; // test graph 1
ArrayList<ArrayList<Integer>> adjList = newArrayList<ArrayList<Integer>>(totalVertices);
for (inti = 0; i < totalVertices; i++) {
adjList.add(newArrayList<Integer>());
}
// test graph 1, cycle - true
// addEdge(adjList, 0, 1);
// addEdge(adjList, 1, 2);
// addEdge(adjList, 2, 3);
// addEdge(adjList, 3, 1);
// test graph 2, cycle - false
addEdge(adjList, 0, 1);
addEdge(adjList, 2, 1);
addEdge(adjList, 2, 3);
addEdge(adjList, 1, 3);
display(adjList);
System.out.println("\nhas cycle: " + hasCycleDirected(adjList));
}
privatestaticvoidaddEdge(ArrayList<ArrayList<Integer>> adjList, intu, intv) {
adjList.get(u).add(v);
// adjList.get(v).add(u);
}
publicstaticvoiddisplay(ArrayList<ArrayList<Integer>> adjList) {
for (inti = 0; i < adjList.size(); i++) {
System.out.println(i + ": " + adjList.get(i));
}
}
// O(V+E) Time
privatestaticbooleanhasCycleDirected(ArrayList<ArrayList<Integer>> adjList) {
returndepthFirstTraverse(adjList);
}
privatestaticbooleandepthFirstTraverse(ArrayList<ArrayList<Integer>> adjList) {
boolean[] visited = newboolean[adjList.size()];
// to track 'Back Edge' in recursion stack
boolean[] recursionStack = newboolean[adjList.size()];
for (inti = 0; i < adjList.size(); i++) {
if (visited[i] == false) {
if (dfsRecursion(adjList, i, visited, recursionStack)) {
returntrue;
}
}
}
returnfalse;
}
privatestaticbooleandfsRecursion(ArrayList<ArrayList<Integer>> adjList, intsrc, boolean[] visited,
boolean[] recursionStack) {
visited[src] = true;
recursionStack[src] = true; // src currently in recursive call stack
for (Integerneighbor : adjList.get(src)) {
if (visited[neighbor] == false) {
if (dfsRecursion(adjList, neighbor, visited, recursionStack) == true) {
returntrue; // cycle exists
}
} elseif (recursionStack[neighbor] == true)
returntrue;
}
recursionStack[src] = false; // src is now removed from the call stack
returnfalse;
}
}