-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSortBfs.java
57 lines (47 loc) · 1.46 KB
/
TopologicalSortBfs.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
package graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class TopologicalSortBfs implements TopologicalSort {
private Graph graph;
public TopologicalSortBfs(Graph graph) {
this.graph = graph;
}
@Override
// Time Complexity: O(V + E)
public List<Integer> sort() {
int[] inDegree = new int[graph.getVerticesCount()];
List<Integer> result = new ArrayList<>();
for (int i = 0; i < graph.getVerticesCount(); i++) {
inDegree[i] = graph.degree(i);
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < graph.getVerticesCount(); i++) {
if (inDegree[i] == 0) {
queue.add(i);
}
}
while (!queue.isEmpty()) {
int node = queue.poll();
result.add(node);
for (int adj : graph.adjacent(node)) {
inDegree[adj]--;
if (inDegree[adj] == 0) {
queue.add(adj);
}
}
}
return result;
}
public static void main(String[] args) {
Graph graph = new DirectedGraphAdjacencyList(5);
graph.addEdge(0, 2);
graph.addEdge(0, 3);
graph.addEdge(2, 3);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
TopologicalSort sort = new TopologicalSortBfs(graph);
System.out.println(sort.sort());
}
}