Sub topic 2
Kahn's Algorithm
This chapter assumes you can read Python, represent a graph as an adjacency list, and follow breadth-first and depth-first search. In the code, an edge u -> v means u must come before v.
Kahn's Algorithm
A node's in-degree is the number of edges pointing into it. A node with in-degree zero has no unmet prerequisites, so it can go next. Kahn's algorithm puts every such node in a queue. It then repeatedly removes a node from the queue, adds it to the output, and lowers the in-degree of each of its successors. When a successor's in-degree drops to zero, it joins the queue.
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']Topological Sort with Depth-First Search
The DFS approach appends a node to the output only after all of its descendants have finished. Every node therefore finishes after the nodes that depend on it. Reversing the finishing order gives a valid topological order.
def topo_sort_dfs(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {}
order = []
def visit(u):
color[u] = GRAY
for v in graph.get(u, []):
c = color.get(v, WHITE)
if c == GRAY:
raise ValueError("graph has a cycle")
if c == WHITE:
visit(v)
color[u] = BLACK
order.append(u)
for u in graph:
if color.get(u, WHITE) == WHITE:
visit(u)
order.reverse()
return order
print(topo_sort_dfs({"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}))
# ['a', 'c', 'b', 'd']Detecting Cycles While Sorting
Both algorithms can detect a cycle at no extra cost.
- Kahn: A node on a cycle never reaches in-degree zero, so it never enters the output. If
len(order)is less than the number of nodes, the graph has a cycle. - DFS: GRAY means the node is still on the recursion stack. An edge into a GRAY node points back to an ancestor, which closes a cycle.
Running Time and Memory
| Algorithm | Time | Extra space |
|---|---|---|
| Kahn | O(V + E) | O(V) for in-degrees and the queue |
| DFS | O(V + E) | O(V) for colors and the recursion stack |
Each node is processed once and each edge is examined once. The recursive DFS can exceed Python's default recursion limit of about 1000 on long chains. Kahn's algorithm is iterative and does not have this problem.
Exercise
What does toposortkahn do with {"a": ["b"], "b": ["c"], "c": ["b"]}, and why?
Show answer
The in-degrees are a=0, b=2, c=1. The algorithm outputs a, which lowers b's in-degree to 1. The queue is then empty. Only 1 of 3 nodes was output, so the function raises ValueError("graph has a cycle"). The cycle is b -> c -> b.