Sub topic 9
Directed Graphs: Kahn's Algorithm and Topological Order
This chapter assumes you know adjacency lists, the idea of in-degree, and breadth-first queues. It also assumes you have seen three-color DFS from the previous chapter, because Kahn's algorithm answers the same question from a different direction.
The Working Model
A topological order lists every vertex of a directed graph so that every edge u -> v points forward: u comes before v. Such an order exists exactly when the graph has no directed cycle. If vertices a, b, c form a cycle, each one must come before the next, and that cannot hold for all three at once.
Kahn's algorithm builds a topological order directly:
- Count the in-degree of every vertex. The in-degree is the number of edges pointing into it.
- Put every vertex with in-degree zero into a queue. Nothing has to come before these vertices.
- Remove a vertex from the queue and append it to the order. Decrease the in-degree of each of its successors. Any successor whose in-degree drops to zero joins the queue.
- Repeat until the queue is empty.
If every vertex was removed, the graph is acyclic. If some vertices remain, the graph has a cycle. A vertex on a cycle always keeps at least one incoming edge from another vertex on the same cycle, so its in-degree can never reach zero.
Implementation
from collections import deque
def has_cycle_kahn(adj):
n = len(adj)
indegree = [0] * n
for u in range(n):
for v in adj[u]:
indegree[v] += 1
queue = deque(u for u in range(n) if indegree[u] == 0)
removed = 0
while queue:
u = queue.popleft()
removed += 1
for v in adj[u]:
indegree[v] -= 1
if indegree[v] == 0:
queue.append(v)
return removed < n
print(has_cycle_kahn([[1], [2], [3], [4], [2]])) # True
print(has_cycle_kahn([[1, 2], [3], [3], []])) # FalseEach vertex enters the queue at most once, and each edge is decremented once. That gives O(V + E) time and O(V) extra space. The algorithm uses no recursion, so deep graphs cannot overflow the call stack.
What the Leftover Vertices Tell You
The vertices that are never removed include every vertex on a cycle. They also include every vertex reachable from a cycle, because a downstream vertex keeps the incoming edge from a stuck predecessor. In the graph 2 -> 3 -> 2, 3 -> 5, vertex 5 is left over even though it lies on no cycle. Kahn's algorithm therefore tells you that a cycle exists and roughly where it is, but it does not tell you the exact cycle. For that, use DFS parent pointers, covered in the next chapter.
Common Errors
| Mistake | Effect | Fix |
|---|---|---|
| Comparing `removed` against the number of edges | Wrong answer on most graphs | Compare against the vertex count `n` |
| Seeding the queue with only vertex 0 | Misses other sources and disconnected parts | Enqueue every vertex with in-degree zero |
| Running it on an undirected graph stored with both directions | Every edge looks like a 2-cycle | Use the undirected methods instead |
| Skipping self-loops when counting in-degree | A self-loop `u -> u` goes undetected | Count every edge, including `u -> u` |
Exercise
Run Kahn's algorithm on adj = [[1], [2], [0, 3], []]. Which vertices are removed, and does the function return True or False?
Show answer
No vertex starts with in-degree zero. Vertex 0 has an incoming edge from 2, vertex 1 from 0, vertex 2 from 1, and vertex 3 from 2. The queue starts empty, so removed = 0 < 4 and the function returns True. Vertex 3 is left over only because it sits downstream of the cycle 0 -> 1 -> 2 -> 0.
Exercise
Why does a self-loop u -> u always stop u from being removed?
Show answer
The self-loop adds 1 to u's in-degree, and only removing u could take that 1 away. Since u is never removed while its in-degree is above zero, it stays stuck and the function correctly reports a cycle.