Sub topic 6
Topological Sort with Depth-First Search
Kahn's algorithm builds a topological order from the front by repeatedly removing nodes that have no remaining prerequisites. Depth-first search (DFS) builds the order from the back. It finishes the deepest dependents first and then reverses the finishing sequence. This chapter explains why that works, shows a recursive and an iterative implementation, and covers the mistakes people make most often.
This chapter assumes you can already write a recursive DFS over an adjacency list, read Python dictionaries of lists, and use the definition of a topological order from earlier chapters: for every edge u -> v, u comes before v.
The Key Idea: Finishing Order
During DFS, every node has two moments that matter:
- Discovery is when DFS first reaches the node and starts exploring its outgoing edges.
- Finishing is when DFS has explored every node reachable through those edges and returns from the node.
The algorithm rests on one claim. In a DAG, for every edge u -> v, v finishes before u. If you write nodes down in the order they finish, every edge points backward in that list. Reverse the list and every edge points forward, which is exactly a topological order.
Why the Claim Holds
Look at the moment DFS examines edge u -> v. At that point u is in progress: it has been discovered but not finished. Node v is in one of three states:
- Not yet discovered. DFS visits
vnow, inside the call foru. The call forvmust return before the call forucan, sovfinishes first. - Already finished. Then
vfinished beforeu, which is what we need. - Discovered but not finished. Then
vis on the current recursion stack, belowu, so there is a pathv -> ... -> u. Adding the edgeu -> vcloses a directed cycle. A DAG has no cycles, so this case cannot happen.
Cases 1 and 2 give the claim directly, and case 3 is ruled out for DAGs. Case 3 is also how DFS detects cycles, which the next chapter covers in detail.
The three states are usually called colors:
The Recursive Implementation
Here, graph maps each node to the list of nodes that depend on it, so u -> v means u must come before v.
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']Some details worth noting:
color.get(v, WHITE)andgraph.get(u, [])let the function handle nodes that appear only as edge targets and never as keys.- The outer loop starts a new DFS from every node that is still white. A single DFS from one root reaches only that root's descendants. The outer loop makes sure disconnected parts of the graph and nodes with no incoming edges are all included.
order.append(u)runs after the loop over neighbors. That placement makes this a postorder traversal, and the whole algorithm depends on it.
Tracing the Example
Here is the run on {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}, with a counter that ticks at every discovery and every finish.
| Step | Event | Recursion stack | `order` so far |
|---|---|---|---|
| 1 | discover `a` | a | [] |
| 2 | discover `b` | a, b | [] |
| 3 | discover `d` | a, b, d | [] |
| 4 | finish `d` | a, b | [d] |
| 5 | finish `b` | a | [d, b] |
| 6 | discover `c` (its edge to `d` sees BLACK) | a, c | [d, b] |
| 7 | finish `c` | a | [d, b, c] |
| 8 | finish `a` | (empty) | [d, b, c, a] |
Reversing [d, b, c, a] gives ['a', 'c', 'b', 'd']. Every edge points forward: a before b and c, and both before d.
Check any edge in the diagram and the source's finishing time is larger than the target's. Sorting by decreasing finishing time gives a valid order.
This result differs from Kahn's algorithm on the same graph, which produces ['a', 'b', 'c', 'd']. Both are correct. The two algorithms simply break ties differently.
An Iterative Version
Python's default recursion limit is about 1000 frames. A dependency chain longer than that, such as a long sequence of migrations, makes the recursive version raise RecursionError. Raising the limit with sys.setrecursionlimit can crash the interpreter on very deep graphs. A safer fix is to manage the stack yourself.
To get postorder right, the explicit stack has to record where each node is in its neighbor list. Storing an iterator per frame does that:
def topo_sort_dfs_iterative(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {}
order = []
for root in graph:
if color.get(root, WHITE) != WHITE:
continue
color[root] = GRAY
stack = [(root, iter(graph.get(root, [])))]
while stack:
u, neighbors = stack[-1]
for v in neighbors:
c = color.get(v, WHITE)
if c == GRAY:
raise ValueError("graph has a cycle")
if c == WHITE:
color[v] = GRAY
stack.append((v, iter(graph.get(v, []))))
break
else:
# Every neighbor has been handled: u finishes now.
stack.pop()
color[u] = BLACK
order.append(u)
order.reverse()
return order
print(topo_sort_dfs_iterative({"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}))
# ['a', 'c', 'b', 'd']
chain = {i: [i + 1] for i in range(5000)}
chain[5000] = []
print(topo_sort_dfs_iterative(chain)[:5])
# [0, 1, 2, 3, 4]The for ... else construct does the key work. The else branch runs only when the iterator runs out without a break, meaning every neighbor is finished, so that is the moment u finishes. When a white neighbor is found, the loop breaks, the neighbor is pushed, and the parent's iterator keeps its position for later. This version visits nodes in the same order as the recursive one, so it returns the same result.
Common Mistakes
Recording preorder instead of postorder
If you append u when it is discovered instead of when it finishes, you get a list that looks plausible but is wrong. Take {"a": ["b", "c"], "c": ["b"], "b": []}. Preorder from a is a, b, c, which puts b before c even though the edge c -> b requires the opposite. Postorder is b, c, a, and reversing it gives the correct a, c, b.
Forgetting to reverse
The raw finishing list is a topological order of the graph with every edge reversed. If you forget order.reverse(), your build system compiles the program before its libraries. To prepend instead of reversing, use collections.deque.appendleft. Calling list.insert(0, u) costs O(V) per call, which makes the whole sort O(V²).
Using one `visited` set
A plain visited set merges GRAY and BLACK into one state. On a DAG, the order still comes out right. On a graph with a cycle, the function silently returns a list that breaks at least one edge, because it cannot tell "currently on the stack" apart from "already done". Keep three states whenever the input could be cyclic.
Mixing up edge direction
The algorithm above expects successor lists (u maps to the nodes that come after it). Some APIs, including Python's graphlib, use predecessor lists instead. If your map gives each node its prerequisites, the postorder itself is already a valid order, and reversing it would be wrong. Before you decide whether to reverse, check which way your edges point.
DFS Compared with Kahn's Algorithm
| Aspect | DFS (reverse postorder) | Kahn's algorithm |
|---|---|---|
| Builds the order | Back to front | Front to back |
| Extra bookkeeping | Color per node, call stack | In-degree per node, queue |
| Partial sort from one target | Natural | Needs a reachability pass first |
| Cycle evidence | The GRAY stack holds the cycle | Only the set of unprocessed nodes |
| Recursion depth risk | Yes, unless written iteratively | None |
| Easy to group into parallel levels | No | Yes |
Both algorithms run in O(V + E) time, which a later chapter analyzes.
Exercise
Run toposortdfs on {"x": ["y"], "w": ["y", "z"], "y": ["z"], "z": []} and give the finishing order and the final result. Assume dictionary keys are iterated in insertion order.
Show answer
The outer loop starts at x. It discovers x and then y, and from y it discovers z. z finishes, then y, then x. Next the outer loop reaches w, whose neighbors y and z are both BLACK, so w finishes. The finishing order is [z, y, x, w], and reversing it gives ['w', 'x', 'y', 'z'].
Exercise
A teammate changes visit so that it appends u right after setting color[u] = GRAY and still reverses at the end. Give a small DAG where the result is not a topological order.
Show answer
Use {"a": ["b"], "b": []} with "b" listed first: {"b": [], "a": ["b"]}. The outer loop visits b first and records [b], then visits a and records [b, a]. Reversing gives [a, b], which happens to be correct, so a better example is {"a": ["b", "c"], "c": ["b"], "b": []}. Preorder is [a, b, c], and the reversed list is [c, b, a]. That puts c and b before a, which breaks the edges a -> b and a -> c.
Exercise
Your dependency map gives each package its prerequisites, for example {"app": ["lib"], "lib": ["utils"], "utils": []}. If you run the DFS postorder over this map without reversing, what do you get, and is it a valid install order?
Show answer
DFS from app discovers lib and then utils. utils finishes first, then lib, then app, so the postorder is [utils, lib, app]. Because the edges point from each package to its prerequisites, this postorder is already a valid install order. Reversing it would install app first, which is wrong.