Sub topic 6
Topological Sort with Depth-First Search
This chapter assumes you know recursive depth-first search (DFS) on an adjacency list, how a Python dictionary represents a graph, and the definition of a topological order from earlier chapters. Kahn's algorithm builds an order from the front by removing sources. The DFS approach builds the order from the back instead: a node is placed only after everything that must come after it has been placed.
The Core Idea: Finishing Order
During DFS, a node finishes when the search has fully explored every node reachable from it. Suppose an edge u → v means "u must come before v." Then v always finishes before u does. Reverse the finishing sequence and every edge points forward, which is a topological order.
Each node is tracked with one of three colors:
| Color | Meaning |
|---|---|
| WHITE | Not yet visited |
| GRAY | Visit started but not finished, so the node is on the current recursion path |
| BLACK | Finished: the node and all its descendants are done |
The Implementation
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']The outer loop starts a fresh DFS from every node that is still white. A single search from one node may not reach the whole graph, so the loop makes sure disconnected parts are covered too.
Tracing the Example
visit(a)turns a gray and descends to b.visit(b)descends to d. Node d has no outgoing edges, so it finishes first andorder = [d].- b finishes, so
order = [d, b]. - Back in a, the search moves to c. Its neighbor d is already black, so the search skips it, and c finishes:
order = [d, b, c]. - a finishes:
order = [d, b, c, a]. - Reversing gives
[a, c, b, d].
This answer differs from the one Kahn's algorithm gives on a similar graph. Both are valid, because a graph often has more than one topological order.
Why It Is Correct
Consider any edge u → v at the moment DFS examines it from u:
- If v is white, DFS visits v now, and v finishes before u.
- If v is black, v has already finished, so it finished before u.
- If v is gray, v is an ancestor on the current path, so v → … → u → v forms a cycle. The next chapter covers this case.
In a DAG only the first two cases happen. That means v finishes before u for every edge, so after the reversal u comes before v.
Common Errors
- Appending too early. If you add u to
orderwhen the visit starts (preorder), the result is not a topological order. The append has to come after the loop over neighbors. - Forgetting to reverse. The raw finishing order is a valid order for the reversed graph, which is the opposite of what you usually want.
- Using two colors instead of three. A plain
visitedset cannot tell "on the current path" apart from "already finished," so it either misses cycles or reports false ones. - Recursion depth. CPython's default recursion limit is about 1000. A long dependency chain will raise
RecursionError, so for large graphs rewritevisitwith an explicit stack.
Exercise
What does toposortdfs return for {"x": ["y"], "y": [], "z": ["y"]}?
Show answer
['z', 'x', 'y']. Visiting x finishes y and then x. Node y is already black, so the outer loop next starts from z, which finishes last. The finishing order [y, x, z] reversed is [z, x, y].
Exercise
Show with the graph a -> b, a -> c, c -> b why appending nodes in preorder (when the visit starts) fails, assuming a's neighbors are listed as [b, c].
Show answer
Preorder visits a, then b, then c, which gives [a, b, c]. The edge c -> b requires c before b, so this sequence breaks that constraint. Postorder gives [b, c, a], and reversing it gives [a, c, b], which is valid.