-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSorting.java
More file actions
64 lines (54 loc) · 1.56 KB
/
TopologicalSorting.java
File metadata and controls
64 lines (54 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
package Graph;
import java.util.*;
public class TopologicalSorting {
private boolean[] visited;
private boolean[] onStack;
private int[] pathTo;
private boolean hasCycle = false;
private Stack<Integer> cycle;
private Stack<Integer> postOrder;
public TopologicalSorting(DirectedGraph g) {
visited = new boolean[g.V()];
onStack = new boolean[g.V()];
pathTo = new int[g.V()];
postOrder = new Stack<Integer>();
for (int i = 0; i < g.V(); i++) {
if (!visited[i]) {
dfs(g, i);
}
}
}
public void dfs(DirectedGraph g, int v) {
visited[v] = true;
onStack[v] = true;
for (int w : g.adj(v)) {
if (hasCycle) return;
if (!visited[w]) {
pathTo[w] = v;
dfs(g, w);
}
else if (onStack[w]) {
hasCycle = true;
cycle = new Stack<Integer>();
cycle.push(w);
for (int x = v; x != w; x = pathTo[x]) {
cycle.push(x);
}
cycle.push(w);
}
}
onStack[v] = false;
postOrder.push(v);
}
public Iterable<Integer> topoOrder() {
if (hasCycle) return null;
List<Integer> list = new ArrayList<Integer>();
while (!postOrder.isEmpty()) {
list.add(postOrder.pop());
}
return list;
}
public boolean hasCycle() {
return hasCycle;
}
}