-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTopological.java
More file actions
33 lines (28 loc) · 947 Bytes
/
Copy pathTopological.java
File metadata and controls
33 lines (28 loc) · 947 Bytes
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
public class Topological {
/* An implementation of topological sort for
* Edge weighted DAGs */
private boolean[] marked;
private Stack<Integer> reversePost;
/* Constructor */
public Topological(EdgeWeightedDigraph G) {
// initialise arrays
this.marked = new boolean[G.V()];
this.reversePost = new Stack<Integer>();
// perform DFS over all vertices
for (int v = 0; v < G.V(); v++)
if (!marked[v]) dfs(G, v);
}
/* Recursive Depth First Search method */
private void dfs(EdgeWeightedDigraph G, int v) {
marked[v] = true;
// visit all adjacent unmarked vertices
for (int w : G.adj(v))
if (!marked[w]) dfs(G, w);
// once done with this vertex, push on stack
reversePost.push(v);
}
/* API: Return topological sort order */
public Iterable<Integer> order() {
return reversePost;
}
}