-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectedCycle.java
More file actions
65 lines (51 loc) · 1.56 KB
/
DirectedCycle.java
File metadata and controls
65 lines (51 loc) · 1.56 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
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
public class DirectedCycle {
private boolean[] marked; // marked[v] = has vertex v been marked?
private int edgeTo []; // edgeTo[v] = previous vertex on path to v
private boolean[] onStack; // onStack[v] = is vertex on the stack?
private Stack<Integer> cycle; //directed cycle (null if no such cycle exists)
public DirectedCycle(Digraph G) {
marked = new boolean[G.V()];
onStack = new boolean[G.V()];
edgeTo = new int[G.V()];
for (int i = 0; i < G.V(); i++) {
if (!marked[i] && cycle == null) dfs(G,i);
}
}
private void dfs(Digraph G, int v) {
onStack[v]= true;
marked[v]= true;
for (int w : G.adj(v)) {
if (cycle != null) return;
else if (!marked[w]){
edgeTo[w]=v;
dfs(G,w);
}
else if (onStack[w]=true) {
cycle = new Stack<Integer>();
for (int x = v; x != w; x=edgeTo[x]) {
cycle.push(x);
}
cycle.push(w);
cycle.push(v);
}
}
onStack[v]=false;
}
public boolean hasCycle() { return cycle!=null; }
public Iterable<Integer> cycle() { return cycle; }
public static void main(String[] args) throws Exception {
Digraph G = new Digraph();
DirectedCycle finder = new DirectedCycle(G);
if (finder.hasCycle()) {
StdOut.print("Directed cycle: ");
for (int v : finder.cycle()) {
StdOut.print(v + " ");
}
StdOut.println();
}
else {
StdOut.println("No directed cycle");
}
StdOut.println();
}
}