Sub topic 11
Topological Sorting from Finish Order
This chapter assumes you know recursive DFS, the full-graph outer loop that builds a DFS forest, finish times (post-order), and three-color cycle detection from the earlier chapters.
What a Topological Order Is
A topological order of a directed graph is a list of all its vertices in which every edge u → v has u before v. Edges usually mean "must happen before": a course prerequisite, a build dependency, or a step in getting dressed.
Only a directed acyclic graph (DAG) has a topological order. If there is a cycle a → b → c → a, then a must come before itself, which is impossible.
The Key Fact: Edges Point Toward Earlier Finishers
Look at what happens to an edge u → v while DFS is exploring u. Vertex v can be in one of three states:
| State of `v` when `u` examines the edge | What follows | Does `v` finish before `u`? |
|---|---|---|
| White (unvisited) | `v` becomes a descendant of `u` | Yes, children finish first |
| Black (finished) | `v` already finished | Yes |
| Gray (on the current path) | This is a back edge, so there is a cycle | Not possible in a DAG |
In a DAG, every edge points from a vertex that finishes later to one that finishes earlier. If you sort vertices by decreasing finish time, every edge points forward, and that sorted list is a topological order. To get it, append each vertex when it finishes and then reverse the list.
The Algorithm
def topological_sort(graph):
visited = set()
postorder = []
def visit(node):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
postorder.append(node) # appended when the node finishes
for node in graph:
if node not in visited:
visit(node)
return postorder[::-1]
deps = {
"shirt": ["tie"],
"tie": ["jacket"],
"pants": ["shoes", "jacket"],
"shoes": [],
"jacket": [],
}
print(topological_sort(deps)) # ['pants', 'shoes', 'shirt', 'tie', 'jacket']Here is the trace. DFS starts at shirt, goes to tie, then jacket. These three finish in the order jacket, tie, shirt. The outer loop then starts a new tree at pants. From there, shoes finishes, jacket is skipped because it is already visited, and pants finishes. The post-order is [jacket, tie, shirt, shoes, pants], and reversing it gives the result above.
The outer loop matters. Without it, vertices that cannot be reached from the first start vertex would be missing. The running time is the same O(V + E) as plain DFS, plus O(V) for the reversal.
Common Errors
- Using discovery order instead of finish order. Pre-order is not a topological order in general. With
depsabove, a pre-order could placejacketbeforepants, which breaks the edgepants → jacket. - Forgetting to reverse. Post-order alone lists dependencies first. That is fine if you want "build these first" order, but it is the reverse of the definition used here.
- Ignoring cycles. The plain version returns an order even for a cyclic graph, and that order is wrong. Add the gray check whenever the input might not be a DAG:
WHITE, GRAY, BLACK = 0, 1, 2
def topological_sort_checked(graph):
color = {node: WHITE for node in graph}
postorder = []
def visit(node):
color[node] = GRAY
for neighbor in graph[node]:
if color[neighbor] == GRAY:
raise ValueError(f"cycle through {neighbor!r}")
if color[neighbor] == WHITE:
visit(neighbor)
color[node] = BLACK
postorder.append(node)
for node in graph:
if color[node] == WHITE:
visit(node)
return postorder[::-1]
print(topological_sort_checked({"a": ["b"], "b": []})) # ['a', 'b']
try:
topological_sort_checked({"a": ["b"], "b": ["a"]})
except ValueError as e:
print(e) # cycle through 'a'Exercise
Run topological_sort on {"a": ["c"], "b": ["c"], "c": ["d"], "d": []}. What does it return, and why can c never appear before a?
Show answer
DFS from a visits c, then d. The finish order is d, c, a. Then b finishes, so the post-order is [d, c, a, b] and the result is ['b', 'a', 'c', 'd']. When a examines the edge a → c, c is either white, so it becomes a descendant and finishes first, or already black. Either way c finishes before a, so after reversal a comes before c.
Exercise
Why does the proof fail when the graph has a cycle?
Show answer
In a cycle, some edge u → v is examined while v is still gray, meaning v is an ancestor of u on the current path. That makes it a back edge, and v finishes after u. The reversed post-order then puts v before u, which breaks the edge u → v.