Topological Sort
Order the vertices of a directed graph so that every edge points forward, or find the cycle that makes it impossible.
A directed graph has nn - 1[a, b]abab
Example 1
Output: [4, 5, 0, 2, 3, 1]
Explanation: every arrow goes from an earlier entry to a later one. [5, 4, 2, 3, 1, 0] is also correct.
Example 2
Output: []
Explanation: the arrows go round in a loop, 0 to 1 to 2 and back to 0. Whichever vertex is listed first, the arrow into it points backward.
The Idea
Picture six jobs on a to-do list, numbered 0 to 5, where some jobs have to wait for others. The arrow 5 → 0 in Example 1 says that job 5 must be finished before job 0 can start. A schedule that respects every arrow is what the problem asks for, and such an order of the vertices is called a topological order. Finding one is a topological sort.
The left half of the picture shows the graph from Example 1. Next to each vertex is its indegree, the number of arrows coming into it. Vertex 0 has two arrows coming in, from 5 and from 4, so its indegree is 2. Vertex 2 has one, from 5. Vertices 4 and 5, drawn in orange, have indegree 0.
So which job can go first? Not 0, because 5 and 4 must come before it. A vertex with indegree 0 waits for nothing, so 4 or 5 can start the list. Say 4 goes first. Its arrows to 0 and 1 are now kept, whatever comes next, so we can cross them off. That drops the indegree of 0 from 2 to 1, and of 1 from 2 to 1.
Next comes 5, the other vertex with indegree 0. Crossing off its arrows drops 0 to indegree 0 and 2 to indegree 0, so both are ready now. Placing 0 crosses off nothing, because no arrow leaves 0. Placing 2 makes 3 ready, and placing 3 makes 1 ready. The list is 4, 5, 0, 2, 3, 1, and in the right half of the picture every arrow of the graph points to the right.
Now try Example 2. Each of its three vertices has one arrow coming in, so no vertex has indegree 0 and nothing can start the list. The vertices wait on each other in a loop, which is called a cycle. A graph with arrows and no cycle is a DAG, short for directed acyclic graph, and every DAG has a topological order.
So the whole method is one move, repeated: take a vertex whose indegree has dropped to 0, list it, and cross off its outgoing arrows. If the moves run out before every vertex is listed, the vertices left over are stuck behind a cycle. This method is known as Kahn's algorithm.
Solution Approach
Kahn's algorithm needs three decisions: how to store the arrows and the indegrees, where to keep the vertices that are ready, and how to notice a cycle. A depth-first version is an optional alternative.
Storing the arrows and the indegrees
Crossing off the arrows that leave a vertex means finding them fast. So the edge pairs become an adjacency list: for each vertex, a list of the vertices its arrows point to. In Example 1, vertex 4 gets the list [0, 1], vertex 5 gets [0, 2], vertex 2 gets [3] and vertex 3 gets [1]. The lists of 0 and 1 stay empty.
The same pass over the edges counts the arrows into each vertex. For Example 1 that gives the indegrees 2, 2, 1, 1, 0, 0 for vertices 0 to 5, the labels in the picture.
Keeping the ready vertices
Where do the vertices with indegree 0 wait until they are listed? Searching all the vertices for one after every step would cost a full scan each time. Instead, a vertex goes into a queue at the moment its indegree reaches 0. Here the queue is an ArrayDeque
Does a vertex need a mark so that it is not queued twice? No. A vertex enters the queue only when its count drops to exactly 0, and the count only goes down, so each vertex is queued once.
Noticing a cycle
How does the code know that a cycle blocked the order? Vertices on a cycle never reach indegree 0, so they never reach the queue. When the queue runs empty, the list is shorter than n
Leaving out this length check is a real trap. Take four vertices with the arrows 0 → 1, 1 → 2, 2 → 1 and 2 → 3. Without the check, the method returns [0][]
Optional: a depth-first version
Depth-first search (DFS) follows arrows as far as they go before backing up. To get an order from it, push a vertex onto a stack only after every vertex reachable from it is finished. The method below takes the adjacency list adjvisited
static void dfs(int u, List<List<Integer>> adj, boolean[] visited, Deque<Integer> stack) {
visited[u] = true;
for (int next : adj.get(u)) {
if (!visited[next]) {
dfs(next, adj, visited, stack);
}
}
stack.push(u); // pushed after every vertex reachable from u
}
Calling dfs[5, 4, 2, 3, 1, 0]uuu
Two traps come with it. Recording each vertex when the search first enters it gives [0, 1, 2, 3, 4, 5]dfs[0, 1, 2]
Java Solution
The method topoSort
- First, build the adjacency list
, one empty list per vertex, and the arrayadj . For each pairindegree , addedge to the list ofedge[1] and add one toedge[0] .indegree[edge[1]] - Create
, anqueue , and add everyArrayDeque whose indegree is 0.vertex - Create the list
. While the queue is not empty, take the vertexorder from its front and append it tou .order - For each vertex
in the list ofnext , loweru by one. If it reaches 0, addindegree[next] to the queue.next - When the queue is empty, return
if it holds allorder vertices, and an empty list otherwise.n
The main
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
public class TopologicalSort {
// Kahn's algorithm. Returns an empty list if the graph has a cycle.
public static List<Integer> topoSort(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
int[] indegree = new int[n];
for (int[] edge : edges) {
adj.get(edge[0]).add(edge[1]); // arrow edge[0] -> edge[1]
indegree[edge[1]]++; // one more arrow into edge[1]
}
Deque<Integer> queue = new ArrayDeque<>();
for (int vertex = 0; vertex < n; vertex++) {
if (indegree[vertex] == 0) {
queue.add(vertex); // nothing has to come before it
}
}
List<Integer> order = new ArrayList<>();
while (!queue.isEmpty()) {
int u = queue.poll();
order.add(u);
for (int next : adj.get(u)) {
indegree[next]--; // the arrow u -> next is now kept
if (indegree[next] == 0) {
queue.add(next); // everything before next is placed
}
}
}
return order.size() == n ? order : new ArrayList<>();
}
public static void main(String[] args) {
int[][] example1 = {{5, 0}, {5, 2}, {4, 0}, {4, 1}, {2, 3}, {3, 1}};
int[][] example2 = {{0, 1}, {1, 2}, {2, 0}};
int[][] noArrows = {};
int[][] partCycle = {{0, 1}, {1, 2}, {2, 1}, {2, 3}}; // 1 and 2 wait on each other
int[][] selfLoop = {{1, 1}}; // 1 waits on itself
int[][] chain = {{3, 2}, {2, 1}, {1, 0}};
System.out.println(topoSort(6, example1));
System.out.println(topoSort(3, example2));
System.out.println(topoSort(3, noArrows));
System.out.println(topoSort(4, partCycle));
System.out.println(topoSort(2, selfLoop));
System.out.println(topoSort(4, chain));
}
}
Running it prints:
[4, 5, 0, 2, 3, 1]
[]
[0, 1, 2]
[]
[]
[3, 2, 1, 0]
Example 1 comes out as [4, 5, 0, 2, 3, 1][][0, 1, 2]
The fourth and fifth lines are both [][3, 2, 1, 0]
Complexity
The work is one pass over the edges to build the lists, then one turn for each vertex as it leaves the queue. Here V is the number of vertices (n
- Time: O(V + E), because each edge is read once to fill
andadj , each vertex enters the queue at most once, and each arrow is crossed off once.indegree - Space: O(V + E), because the adjacency list stores every edge once, while
, the queue andindegree each hold at most V entries.order
For the same idea with courses and the courses they require first, see