Kahn's algorithm: take what has no prerequisites left
🌍 In real life. Planning a degree: each term, you can take any course whose prerequisites you have already passed. Once you pass Programming, it no longer blocks Algorithms. Keep taking whatever is unblocked, and you work through the whole programme in an order that never breaks a prerequisite.
That is Kahn's algorithm, the most natural way to find a topological order. It keeps a pool of jobs with no prerequisites left, takes one, crosses out the arrows leaving it, and adds any job that this frees to the pool.
The idea in one sentence: Kahn's algorithm works out every in-degree, puts the vertices with in-degree 0 in a ready pool, and repeatedly takes one, appends it to the order and lowers the in-degree of each vertex it points to, adding any that reach 0 to the pool.
Its words:
- ready pool: the vertices with no arrows left coming in; any of them may go next
- removing a vertex: taking it into the order and deleting its outgoing arrows, which lowers its targets' in-degrees
- tie-break: a rule for which ready vertex goes first; here a min-heap takes the alphabetically first, so the answer is always the same
- round: all the vertices that are ready at the same time; the number of rounds is the fewest terms needed if you take every ready course each term
How it works, step by step:
- count each vertex's in-degree
- put every vertex with in-degree 0 in the ready pool
- take a vertex from the pool and append it to the order
- for each arrow it has to w, lower w's in-degree; if it reaches 0, add w to the pool
- when the pool is empty: if every vertex is in the order, it is a topological order; otherwise there is a cycle: each left-over vertex is on one or comes after one
Watch the courses leave one at a time; each taken course's arrows fade, and the courses it frees turn blue:
Why it is correct. A vertex enters the pool only when its in-degree reaches 0, which means every vertex with an arrow into it is already in the order. So whenever a vertex is appended, everything that must come before it is already placed: every arrow points forward. If the graph is a DAG, the pool can't run dry early: the vertices not yet placed form a smaller DAG, which always has a source (Lesson 52.1), and that source has in-degree 0 in the pool. If vertices are left over when the pool runs dry, each still has an arrow coming in from another left-over vertex, and walking those arrows backwards must go round a cycle.
What it costs, by counting. Counting in-degrees looks at each arrow once; then each vertex enters and leaves the pool once, and each arrow is crossed out once: O(V + E). With a plain list as the pool that is the whole cost; the min-heap used here for a fixed tie-break adds O(log V) per vertex, so O(V log V + E). For the six courses: 6 vertices taken and 6 arrows crossed out.
import heapq
def kahn(graph):
indeg = {v: 0 for v in graph}
for v in graph:
for w in graph[v]:
indeg[w] += 1
ready = [v for v in graph if indeg[v] == 0]
heapq.heapify(ready) # take the alphabetically first ready job
order = []
while ready:
v = heapq.heappop(ready)
order.append(v)
for w in graph[v]:
indeg[w] -= 1 # v is done, so its arrow to w is gone
if indeg[w] == 0:
heapq.heappush(ready, w)
return order if len(order) == len(graph) else None # some left over: a cycle
print(kahn({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}))
print(kahn({"A": ["B"], "B": ["C"], "C": ["A"], "D": ["A"]})) # a cycle
def min_rounds(graph):
indeg = {v: 0 for v in graph}
for v in graph:
for w in graph[v]:
indeg[w] += 1
now = [v for v in graph if indeg[v] == 0]
rounds = done = 0
while now:
rounds += 1 # everything ready is done together
done += len(now)
nxt = []
for v in now:
for w in graph[v]:
indeg[w] -= 1
if indeg[w] == 0:
nxt.append(w)
now = nxt
return rounds if done == len(graph) else -1
print(min_rounds({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}))Mistakes and edge cases.
- adding a vertex to the pool before its in-degree is 0: it goes before something that must come first
- not checking the count at the end: on a graph with a cycle, the loop just stops early and returns a partial order that looks fine; compare its length with the number of vertices
- expecting the same order from any pool: a list used as a stack, a queue or a heap gives different (all valid) orders; use a heap when the answer must be repeatable
- changing the caller's graph: work on a copy of the in-degrees, never by deleting from the input
- vertices with no arrows at all: they have in-degree 0 and go into the pool at the start, so they appear in the order like any other
Quiz
What does this print?
import heapq def kahn(graph): indeg = {v: 0 for v in graph} for v in graph: for w in graph[v]: indeg[w] += 1 ready = [v for v in graph if indeg[v] == 0] heapq.heapify(ready) # take the alphabetically first ready job order = [] while ready: v = heapq.heappop(ready) order.append(v) for w in graph[v]: indeg[w] -= 1 # v is done, so its arrow to w is gone if indeg[w] == 0: heapq.heappush(ready, w) return order if len(order) == len(graph) else None # some left over: a cycle print(kahn({"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}))A graph with a cycle. What does this print?
import heapq def kahn(graph): indeg = {v: 0 for v in graph} for v in graph: for w in graph[v]: indeg[w] += 1 ready = [v for v in graph if indeg[v] == 0] heapq.heapify(ready) # take the alphabetically first ready job order = [] while ready: v = heapq.heappop(ready) order.append(v) for w in graph[v]: indeg[w] -= 1 # v is done, so its arrow to w is gone if indeg[w] == 0: heapq.heappush(ready, w) return order if len(order) == len(graph) else None # some left over: a cycle print(kahn({"A": ["B"], "B": ["A"], "C": ["A"]}))Why does Kahn's algorithm count how many vertices it placed at the end?
- If some were never placed, there is a cycle, so no order exists
- To sort them
- To find the longest path
This puts D before C, although C → D. Which line is wrong?
def kahn(graph, indeg): ready = [v for v in graph if indeg[v] == 0] order = [] while ready: v = ready.pop() order.append(v) for w in graph[v]: indeg[w] -= 1 ready.append(w) return orderTaking every ready course each term, how many terms are needed?
def min_rounds(graph): indeg = {v: 0 for v in graph} for v in graph: for w in graph[v]: indeg[w] += 1 now = [v for v in graph if indeg[v] == 0] rounds = done = 0 while now: rounds += 1 # everything ready is done together done += len(now) nxt = [] for v in now: for w in graph[v]: indeg[w] -= 1 if indeg[w] == 0: nxt.append(w) now = nxt return rounds if done == len(graph) else -1 print(min_rounds({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}))
Coding tasks
Write
kahn(graph): a topological order by Kahn's algorithm, always taking the alphabetically first ready vertex (useheapq). ReturnNoneif the graph has a cycle.graphmaps every vertex to the vertices that must come after it.Write
min_rounds(graph): if every ready job is done together in one round, how many rounds does it take to do them all? Return-1if a cycle makes it impossible.