-
Notifications
You must be signed in to change notification settings - Fork 1
/
TopologicalSort.java
63 lines (53 loc) · 2.69 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.*;
class TopologicalSort {
public static List<Integer> sort(int vertices, int[][] edges) {
List<Integer> sortedOrder = new ArrayList<>();
if (vertices <= 0)
return sortedOrder;
// a. Initialize the graph
HashMap<Integer, Integer> inDegree = new HashMap<>(); // count of incoming edges for every vertex
HashMap<Integer, List<Integer>> graph = new HashMap<>(); // adjacency list graph
for (int i = 0; i < vertices; i++) {
inDegree.put(i, 0);
graph.put(i, new ArrayList<Integer>());
}
// b. Build the graph
for (int i = 0; i < edges.length; i++) {
int parent = edges[i][0], child = edges[i][1];
graph.get(parent).add(child); // put the child into it's parent's list
inDegree.put(child, inDegree.get(child) + 1); // increment child's inDegree
}
// c. Find all sources i.e., all vertices with 0 in-degrees
Queue<Integer> sources = new LinkedList<>();
for (Map.Entry<Integer, Integer> entry : inDegree.entrySet()) {
if (entry.getValue() == 0)
sources.add(entry.getKey());
}
// d. For each source, add it to the sortedOrder and subtract one from all of its children's in-degrees
// if a child's in-degree becomes zero, add it to the sources queue
while (!sources.isEmpty()) {
int vertex = sources.poll();
sortedOrder.add(vertex);
List<Integer> children = graph.get(vertex); // get the node's children to decrement their in-degrees
for (int child : children) {
inDegree.put(child, inDegree.get(child) - 1);
if (inDegree.get(child) == 0)
sources.add(child);
}
}
if (sortedOrder.size() != vertices) // topological sort is not possible as the graph has a cycle
return new ArrayList<>();
return sortedOrder;
}
public static void main(String[] args) {
List<Integer> result = TopologicalSort.sort(4,
new int[][] { new int[] { 3, 2 }, new int[] { 3, 0 }, new int[] { 2, 0 }, new int[] { 2, 1 } });
System.out.println(result);
result = TopologicalSort.sort(5, new int[][] { new int[] { 4, 2 }, new int[] { 4, 3 }, new int[] { 2, 0 },
new int[] { 2, 1 }, new int[] { 3, 1 } });
System.out.println(result);
result = TopologicalSort.sort(7, new int[][] { new int[] { 6, 4 }, new int[] { 6, 2 }, new int[] { 5, 3 },
new int[] { 5, 4 }, new int[] { 3, 0 }, new int[] { 3, 1 }, new int[] { 3, 2 }, new int[] { 4, 1 } });
System.out.println(result);
}
}