Sub topic 5
Kahn's Algorithm
This chapter assumes you can read Python, represent a graph as an adjacency list, and use a queue. You should also know from the previous chapter that a topological order exists exactly when the graph is a DAG.
The Working Model
Kahn's algorithm builds a topological order from the front. It relies on one fact: every DAG has at least one node with no incoming edges. Such a node depends on nothing, so it can safely go first.
The in-degree of a node is the number of edges pointing into it. A node with in-degree zero has no unmet dependencies. The algorithm works like this:
- Count the in-degree of every node.
- Put every node with in-degree zero into a queue.
- Remove a node from the queue and append it to the output.
- For each edge leaving that node, decrease the target's in-degree by one. If a target's in-degree reaches zero, add it to the queue.
- Repeat until the queue is empty.
Decreasing the in-degrees has the same effect as deleting the node and its outgoing edges from the graph. What remains is still a DAG, so a new zero in-degree node always appears, until every node has been output.
Implementation
The graph maps each node to the nodes that depend on it. An edge u -> v means u must come before v.
from collections import deque
def topo_sort_kahn(graph):
"""graph maps each node to a list of nodes that depend on it (u -> v means u before v)."""
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
queue = deque(u for u, d in indegree.items() if d == 0)
order = []
while queue:
u = queue.popleft()
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
if len(order) != len(indegree):
raise ValueError("graph has a cycle")
return order
courses = {
"intro": ["data_structures", "discrete_math"],
"discrete_math": ["algorithms"],
"data_structures": ["algorithms"],
"algorithms": [],
}
print(topo_sort_kahn(courses))
# ['intro', 'data_structures', 'discrete_math', 'algorithms']Here is the trace. Only intro starts at in-degree zero. Removing it drops data_structures and discrete_math to zero, and both are enqueued. Removing each of those decrements algorithms, which reaches zero only after both are gone.
The final length check matters. If some nodes never reach in-degree zero, they lie on a cycle or depend on one. A later chapter covers how to report that cycle.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Counting in-degrees only for keys of `graph` | `KeyError` when a node appears only as a target | Use `indegree.get(v, 0) + 1`, as above |
| Reversing the edge direction | Output comes out backwards | Decide once whether `u -> v` means "u before v" and stick to it |
| Enqueuing a node every time it is decremented | Duplicates in the output | Enqueue only when the in-degree becomes exactly zero |
| Skipping the final length check | A cyclic graph silently returns a partial order | Compare `len(order)` with the node count |
| Using `list.pop(0)` as the queue | Quadratic slowdown on large graphs | Use `collections.deque` |
Exercise
Run toposortkahn on {"a": ["c"], "b": ["c", "d"], "c": ["e"], "d": ["e"], "e": []}. What order does it print, and which nodes are in the queue right after "b" is processed?
Show answer
The printed order is ['a', 'b', 'c', 'd', 'e']. At the start, a and b have in-degree 0. Processing a drops c to 1. Processing b drops c to 0 and d to 0, so the queue then holds c and d. Processing c drops e to 1, and processing d drops e to 0, so e comes last.
Exercise
If you replace the deque with a Python list used as a stack (append and pop from the end), is the output still a valid topological order? Why?
Show answer
Yes. A node enters the container only after all of its predecessors have been output, so any removal order respects every edge. Only the particular valid order changes.