Kahn's Algorithm
The DFS-based topological sort works backwards: it finds the tasks that come last first. There is an equally fast method that works forwards, the way a person would schedule: start with the tasks that depend on nothing, do one, cross it off, and see which tasks have become free. This is Kahn's algorithm (1962). It needs no recursion, it detects cycles as a side effect, it can pick among the free tasks by any rule you like, and grouped into rounds it tells you how many parallel steps a schedule needs.
The algorithm
Keep the in-degree of every vertex in the part of the graph not yet output. A vertex whose in-degree is 0 has no unfinished prerequisites, so it is ready.
KAHN(G)
1 for each vertex v: indeg[v] = number of edges entering v
2 R = the set of vertices with indeg 0 // ready vertices
3 L = an empty list
4 while R is not empty
5 remove some vertex u from R and append it to L
6 for each v in G.Adj[u] // delete u's outgoing edges
7 indeg[v] = indeg[v] - 1
8 if indeg[v] == 0
9 add v to R
10 if L has fewer than |V| vertices
11 report "G has a cycle" // the rest all have indeg >= 1
12 return LLine 1 costs (one pass over all adjacency lists). Each vertex enters and leaves once, and each edge is deleted once on line 7. With a queue or stack as , Kahn's algorithm runs in . With a min-heap, it returns the lexicographically smallest topological order (always the smallest ready name first) in time. The animation, like this course's Python, uses that rule.
import heapq
adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F", "G"], "F": [], "G": ["F"]}
def kahn(adj):
indeg = {v: 0 for v in adj}
for u in adj:
for v in adj[u]:
indeg[v] += 1
ready = [v for v in adj if indeg[v] == 0]
heapq.heapify(ready)
print("in-degrees:", indeg, "ready:", sorted(ready))
order = []
while ready:
u = heapq.heappop(ready)
order.append(u)
freed = []
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
heapq.heappush(ready, v)
freed.append(v)
print(f"output {u}; newly ready: {freed or '-'}; ready set {sorted(ready)}")
if len(order) < len(adj):
stuck = [v for v in adj if v not in order]
raise ValueError(f"cycle among {stuck}")
return order
print("order:", " ".join(kahn(adj)))in-degrees: {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 1, 'F': 3, 'G': 1} ready: ['A']
output A; newly ready: ['B', 'C']; ready set ['B', 'C']
output B; newly ready: -; ready set ['C']
output C; newly ready: ['D', 'E']; ready set ['D', 'E']
output D; newly ready: -; ready set ['E']
output E; newly ready: ['G']; ready set ['G']
output G; newly ready: ['F']; ready set ['F']
output F; newly ready: -; ready set []
order: A B C D E G F
The DFS method gave for the same graph; Kahn's algorithm with the smallest-name rule gives . Both are valid: they are two of the graph's nine topological orders.
Why it is correct
Every output vertex is placed after its prerequisites. When is appended to , its in-degree in the remaining graph is 0, so every edge of has already been deleted, which happens only when is output. So precedes in .
If the algorithm stops early, there is a cycle. Suppose becomes empty while a set of vertices remains. Every vertex of has in-degree at least 1 within (edges from output vertices have been deleted). Start anywhere in and repeatedly step backwards along an entering edge; each step stays in . After steps some vertex repeats, and the walk between the two visits is a directed cycle. Conversely, a vertex on a cycle can never reach in-degree 0, since the edge from its cycle predecessor is deleted only after that predecessor is output. So contains all vertices if and only if is acyclic.
The program builds the backward walk to print an actual cycle when Kahn's algorithm gets stuck.
from collections import deque
def kahn_or_cycle(adj):
indeg = {v: 0 for v in adj}
for u in adj:
for v in adj[u]:
indeg[v] += 1
q = deque(v for v in sorted(adj) if indeg[v] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
if len(order) == len(adj):
return "order " + " ".join(order)
rest = set(adj) - set(order)
into = {v: [u for u in rest if v in adj[u]] for v in rest} # entering edges inside the rest
walk, x = [], min(rest)
while x not in walk:
walk.append(x)
x = min(into[x]) # step backwards
cycle = walk[walk.index(x):][::-1]
return f"stuck after {' '.join(order) or 'nothing'}; cycle {' -> '.join(cycle + [cycle[0]])}"
print(kahn_or_cycle({"A": ["B"], "B": ["C"], "C": ["D"], "D": []}))
print(kahn_or_cycle({"A": ["B"], "B": ["C"], "C": ["D", "E"], "D": ["B"], "E": []}))
print(kahn_or_cycle({"A": ["B"], "B": ["A"], "C": ["A", "D"], "D": []}))order A B C D
stuck after A; cycle C -> D -> B -> C
stuck after C D; cycle B -> A -> B
In the second graph is output, after which , and each keep an entering edge from the cycle , and waits behind forever.
Rounds: how many parallel steps?
If any number of tasks can run at once, a natural schedule runs all ready tasks in each round. Kahn's algorithm does that if it processes round by round. The number of rounds equals the number of vertices on a longest path of the DAG, because a vertex becomes ready in round exactly when the longest path ending at it has vertices, and no schedule can beat that: the tasks of a path must run one after another. Longest paths in DAGs, with durations, are the critical paths of project planning.
adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F", "G"], "F": [], "G": ["F"]}
def rounds(adj):
indeg = {v: 0 for v in adj}
for u in adj:
for v in adj[u]:
indeg[v] += 1
current = sorted(v for v in adj if indeg[v] == 0)
result = []
while current:
result.append(current)
nxt = []
for u in current:
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
nxt.append(v)
current = sorted(nxt)
return result
for i, r in enumerate(rounds(adj), 1):
print(f"round {i}: {', '.join(r)}")round 1: A
round 2: B, C
round 3: D, E
round 4: G
round 5: F
Five rounds, matching the longest path , which has five vertices. Tasks and are not on that path and have slack: could slip from round 3 to round 4, or from round 2 to round 3, without delaying .
In C++
With std::priority_queue and std::greater, the C++ version produces the same lexicographically smallest order as the Python program.
#include <cstdio>
#include <functional>
#include <queue>
#include <string>
#include <vector>
int main() {
const std::string names = "ABCDEFG";
const int n = static_cast<int>(names.size());
std::vector<std::vector<int>> adj = {{1, 2}, {3}, {3, 4}, {5}, {5, 6}, {}, {5}};
std::vector<int> indeg(n, 0);
for (const auto& list : adj)
for (int v : list) ++indeg[v];
std::priority_queue<int, std::vector<int>, std::greater<int>> ready;
for (int v = 0; v < n; ++v)
if (indeg[v] == 0) ready.push(v);
std::string order;
while (!ready.empty()) {
int u = ready.top();
ready.pop();
order += names[u];
for (int v : adj[u])
if (--indeg[v] == 0) ready.push(v);
}
if (static_cast<int>(order.size()) < n) std::printf("cycle\n");
else std::printf("order: %s\n", order.c_str());
}order: ABCDEGF
Test yourself
Kahn's algorithm stops with 3 of 8 vertices output. What can you conclude?
- The graph is disconnected
- The graph has a directed cycle among the remaining vertices (or reachable from it)
- The in-degrees were miscounted
- The graph is a tree
Which data structure for the ready set gives the lexicographically smallest topological order?
- A FIFO queue
- A stack
- A min-priority queue keyed by name
- Any of them
Tasks with unlimited workers are run in rounds: each round runs every ready task. How many rounds are needed?
- The number of vertices
- The maximum in-degree
- The number of vertices on a longest path
- The number of sources