-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheckCycleInDirectedGraph.java
68 lines (57 loc) · 1.9 KB
/
CheckCycleInDirectedGraph.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
package graph;
public class CheckCycleInDirectedGraph {
Graph g;
public CheckCycleInDirectedGraph(Graph g) {
this.g = g;
}
public boolean hasCycle() {
boolean[] visited = new boolean[g.getVerticesCount()];
boolean[] recursionStack = new boolean[g.getVerticesCount()];
for (int i = 0; i < g.getVerticesCount(); i++) {
if (!visited[i]) {
if (dfsRecursive(i, visited, recursionStack)) {
return true;
}
}
}
return false;
}
private boolean dfsRecursive(int source, boolean[] visited, boolean[] recursionStack) {
visited[source] = true;
recursionStack[source] = true;
for (int adj : g.adjacent(source)) {
if (!visited[adj]) {
if (dfsRecursive(adj, visited, recursionStack)) {
return true;
}
} else {
if (recursionStack[adj]) {
return true;
}
}
}
recursionStack[source] = false;
return false;
}
public static void main(String[] args) {
Graph g = new DirectedGraphAdjacencyList(6);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 4);
g.addEdge(4, 5);
g.addEdge(1, 3);
g.addEdge(2, 3);
g.addEdge(5, 2);
CheckCycleInDirectedGraph checkGraph = new CheckCycleInDirectedGraph(g);
System.out.println("Graph: " + g);
System.out.println("Graph contains cycle: " + checkGraph.hasCycle());
g = new DirectedGraphAdjacencyList(4);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(0, 2);
g.addEdge(2, 3);
checkGraph = new CheckCycleInDirectedGraph(g);
System.out.println("Graph: " + g);
System.out.println("Graph contains cycle: " + checkGraph.hasCycle());
}
}