-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path03-TopologicalSort.java
46 lines (39 loc) · 1.19 KB
/
03-TopologicalSort.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
package graphs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
/**
* Implementation of topological sorting
* Works for acyclic directed graph (DAG)
* O(n) complexity
*/
public class TopologicalSort {
/**
* Returns a list of all the vertices of the graph in their sorted order.
*/
public static List<Integer> sortedVertices(DirectedGraph graph) {
List<Integer> result = new ArrayList<>();
Stack<Integer> s = new Stack<>();
Arrays.fill(graph.visited, false);
for (int vertex = 0; vertex < graph.vertices; vertex++) {
if (!graph.visited[vertex]) {
topSort(graph, vertex, s);
}
}
Arrays.fill(graph.visited, false);
while (!s.empty()) {
result.add(s.pop());
}
return result;
}
private static void topSort(DirectedGraph graph, int vertex, Stack<Integer> s) {
graph.visited[vertex] = true;
graph.adjacencyList.get(vertex).forEach(neighbour -> {
if (!graph.visited[neighbour.to]) {
topSort(graph, neighbour.to, s);
}
});
s.push(vertex);
}
}