socksshoespantsbelt1while ready:2 u = ready.popleft()3 order.append(u)4 for v in graph[u]:5 indeg[v] -= 16 if indeg[v] == 0:7 ready.append(v)jacketshirtreadyfront: outback: inordersockspantsshirtshoesbeltjacket
Jobs: the front number is the in-degree, arrows still coming inArrows: u → v means u first; a faded arrow is crossed outTokens: a ready job travels through the queue to the orderSix jobs joined by arrows: an arrow from u to v means u must come first. The number on a job is its in-degree, the arrows still coming in. Kahn's algorithm queues every job at 0, then takes the front job, writes it down and crosses out its arrows; a job whose count reaches 0 joins the queue. A loop of arrows keeps its counts above 0, so the run stops short: that is how the algorithm finds a cycle.

Jobs and arrows

  1. Getting dressed is six jobs. An arrow from socks to shoes means socks must come first. Arrows that point one way, with no loop back, form a DAG: a directed acyclic graph. We want a list of jobs where every arrow points forward.

Kahn's algorithm

Checking the answer

The whole function in Python

from collections import deque

def topo_sort(graph):
    indeg = {u: 0 for u in graph}
    for u in graph:
        for v in graph[u]:
            indeg[v] += 1
    ready = deque(u for u in graph if indeg[u] == 0)
    order = []
    while ready:
        u = ready.popleft()
        order.append(u)
        for v in graph[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                ready.append(v)
    if len(order) < len(graph):
        raise ValueError("cycle: no topological order")
    return order

graph = {
    "socks": ["shoes"],
    "pants": ["shoes", "belt"],
    "shirt": ["belt", "jacket"],
    "shoes": [],
    "belt": ["jacket"],
    "jacket": [],
}
print(topo_sort(graph))

What happens

# step 1/10 · Jobs with arrows
a DAG: directed edges, no directed cycle
u -> v means "u before v"
  socks  -> shoes
  pants  -> shoes
  pants  -> belt
  shirt  -> belt
  shirt  -> jacket
  belt   -> jacket

the same graph in Python (each job lists the jobs that wait for it):
graph = {
    "socks": ["shoes"],
    "pants": ["shoes", "belt"],
    "shirt": ["belt", "jacket"],
    "shoes": [],
    "belt": ["jacket"],
    "jacket": [],
}

This queue method is Kahn's algorithm (A. B. Kahn, 1962). Another way, in MIT 6.006 and Sedgewick and Wayne, runs depth-first search and lists the jobs in reverse finishing order; both take O(V + E) time. The order is unique only when every pair of neighbours in the list is joined by an arrow. Here socks, pants and shirt are all ready at the start, so several orders are correct; the queue picks the one the graph lists first.