TExcelTAD
Home › Graph Algorithms › Kahn's Algorithm

Kahn's Algorithm

The DFS-based topological sort works backwards: it finds the tasks that come last first. There is an equally fast method that works forwards, the way a person would schedule: start with the tasks that depend on nothing, do one, cross it off, and see which tasks have become free. This is Kahn's algorithm (1962). It needs no recursion, it detects cycles as a side effect, it can pick among the free tasks by any rule you like, and grouped into rounds it tells you how many parallel steps a schedule needs.

The algorithm

Keep the in-degree of every vertex in the part of the graph not yet output. A vertex whose in-degree is 0 has no unfinished prerequisites, so it is ready.

text
KAHN(G)
1  for each vertex v:  indeg[v] = number of edges entering v
2  R = the set of vertices with indeg 0             // ready vertices
3  L = an empty list
4  while R is not empty
5      remove some vertex u from R and append it to L
6      for each v in G.Adj[u]                       // delete u's outgoing edges
7          indeg[v] = indeg[v] - 1
8          if indeg[v] == 0
9              add v to R
10 if L has fewer than |V| vertices
11     report "G has a cycle"                        // the rest all have indeg >= 1
12 return L

Line 1 costs Θ(V+E)\Theta(V + E) (one pass over all adjacency lists). Each vertex enters and leaves RR once, and each edge is deleted once on line 7. With a queue or stack as RR, Kahn's algorithm runs in Θ(V+E)\Theta(V + E). With a min-heap, it returns the lexicographically smallest topological order (always the smallest ready name first) in O(Vlg⁡V+E)O(V \lg V + E) time. The animation, like this course's Python, uses that rule.

python · try it yourself
import heapq

adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F", "G"], "F": [], "G": ["F"]}

def kahn(adj):
    indeg = {v: 0 for v in adj}
    for u in adj:
        for v in adj[u]:
            indeg[v] += 1
    ready = [v for v in adj if indeg[v] == 0]
    heapq.heapify(ready)
    print("in-degrees:", indeg, "ready:", sorted(ready))
    order = []
    while ready:
        u = heapq.heappop(ready)
        order.append(u)
        freed = []
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                heapq.heappush(ready, v)
                freed.append(v)
        print(f"output {u}; newly ready: {freed or '-'}; ready set {sorted(ready)}")
    if len(order) < len(adj):
        stuck = [v for v in adj if v not in order]
        raise ValueError(f"cycle among {stuck}")
    return order

print("order:", " ".join(kahn(adj)))
in-degrees: {'A': 0, 'B': 1, 'C': 1, 'D': 2, 'E': 1, 'F': 3, 'G': 1} ready: ['A']
output A; newly ready: ['B', 'C']; ready set ['B', 'C']
output B; newly ready: -; ready set ['C']
output C; newly ready: ['D', 'E']; ready set ['D', 'E']
output D; newly ready: -; ready set ['E']
output E; newly ready: ['G']; ready set ['G']
output G; newly ready: ['F']; ready set ['F']
output F; newly ready: -; ready set []
order: A B C D E G F

The DFS method gave A,C,E,G,B,D,FA, C, E, G, B, D, F for the same graph; Kahn's algorithm with the smallest-name rule gives A,B,C,D,E,G,FA, B, C, D, E, G, F. Both are valid: they are two of the graph's nine topological orders.

Why it is correct

Every output vertex is placed after its prerequisites. When uu is appended to LL, its in-degree in the remaining graph is 0, so every edge (w,u)(w, u) of GG has already been deleted, which happens only when ww is output. So ww precedes uu in LL.

If the algorithm stops early, there is a cycle. Suppose RR becomes empty while a set SS of vertices remains. Every vertex of SS has in-degree at least 1 within SS (edges from output vertices have been deleted). Start anywhere in SS and repeatedly step backwards along an entering edge; each step stays in SS. After ∣S∣+1\lvert S \rvert + 1 steps some vertex repeats, and the walk between the two visits is a directed cycle. Conversely, a vertex on a cycle can never reach in-degree 0, since the edge from its cycle predecessor is deleted only after that predecessor is output. So LL contains all vertices if and only if GG is acyclic.

The program builds the backward walk to print an actual cycle when Kahn's algorithm gets stuck.

python · try it yourself
from collections import deque

def kahn_or_cycle(adj):
    indeg = {v: 0 for v in adj}
    for u in adj:
        for v in adj[u]:
            indeg[v] += 1
    q = deque(v for v in sorted(adj) if indeg[v] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    if len(order) == len(adj):
        return "order " + " ".join(order)
    rest = set(adj) - set(order)
    into = {v: [u for u in rest if v in adj[u]] for v in rest}    # entering edges inside the rest
    walk, x = [], min(rest)
    while x not in walk:
        walk.append(x)
        x = min(into[x])                                           # step backwards
    cycle = walk[walk.index(x):][::-1]
    return f"stuck after {' '.join(order) or 'nothing'}; cycle {' -> '.join(cycle + [cycle[0]])}"

print(kahn_or_cycle({"A": ["B"], "B": ["C"], "C": ["D"], "D": []}))
print(kahn_or_cycle({"A": ["B"], "B": ["C"], "C": ["D", "E"], "D": ["B"], "E": []}))
print(kahn_or_cycle({"A": ["B"], "B": ["A"], "C": ["A", "D"], "D": []}))
order A B C D
stuck after A; cycle C -> D -> B -> C
stuck after C D; cycle B -> A -> B

In the second graph AA is output, after which BB, CC and DD each keep an entering edge from the cycle B→C→D→BB \to C \to D \to B, and EE waits behind CC forever.

Rounds: how many parallel steps?

If any number of tasks can run at once, a natural schedule runs all ready tasks in each round. Kahn's algorithm does that if it processes RR round by round. The number of rounds equals the number of vertices on a longest path of the DAG, because a vertex becomes ready in round kk exactly when the longest path ending at it has kk vertices, and no schedule can beat that: the tasks of a path must run one after another. Longest paths in DAGs, with durations, are the critical paths of project planning.

python · try it yourself
adj = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F", "G"], "F": [], "G": ["F"]}

def rounds(adj):
    indeg = {v: 0 for v in adj}
    for u in adj:
        for v in adj[u]:
            indeg[v] += 1
    current = sorted(v for v in adj if indeg[v] == 0)
    result = []
    while current:
        result.append(current)
        nxt = []
        for u in current:
            for v in adj[u]:
                indeg[v] -= 1
                if indeg[v] == 0:
                    nxt.append(v)
        current = sorted(nxt)
    return result

for i, r in enumerate(rounds(adj), 1):
    print(f"round {i}: {', '.join(r)}")
round 1: A
round 2: B, C
round 3: D, E
round 4: G
round 5: F

Five rounds, matching the longest path A→C→E→G→FA \to C \to E \to G \to F, which has five vertices. Tasks BB and DD are not on that path and have slack: DD could slip from round 3 to round 4, or BB from round 2 to round 3, without delaying FF.

In C++

With std::priority_queue and std::greater, the C++ version produces the same lexicographically smallest order as the Python program.

cpp · try it yourself
#include <cstdio>
#include <functional>
#include <queue>
#include <string>
#include <vector>

int main() {
    const std::string names = "ABCDEFG";
    const int n = static_cast<int>(names.size());
    std::vector<std::vector<int>> adj = {{1, 2}, {3}, {3, 4}, {5}, {5, 6}, {}, {5}};
    std::vector<int> indeg(n, 0);
    for (const auto& list : adj)
        for (int v : list) ++indeg[v];
    std::priority_queue<int, std::vector<int>, std::greater<int>> ready;
    for (int v = 0; v < n; ++v)
        if (indeg[v] == 0) ready.push(v);
    std::string order;
    while (!ready.empty()) {
        int u = ready.top();
        ready.pop();
        order += names[u];
        for (int v : adj[u])
            if (--indeg[v] == 0) ready.push(v);
    }
    if (static_cast<int>(order.size()) < n) std::printf("cycle\n");
    else std::printf("order: %s\n", order.c_str());
}
order: ABCDEGF

Test yourself

Kahn's algorithm stops with 3 of 8 vertices output. What can you conclude?

  1. The graph is disconnected
  2. The graph has a directed cycle among the remaining vertices (or reachable from it)
  3. The in-degrees were miscounted
  4. The graph is a tree

Which data structure for the ready set gives the lexicographically smallest topological order?

  1. A FIFO queue
  2. A stack
  3. A min-priority queue keyed by name
  4. Any of them

Tasks with unlimited workers are run in rounds: each round runs every ready task. How many rounds are needed?

  1. The number of vertices
  2. The maximum in-degree
  3. The number of vertices on a longest path
  4. The number of sources