Sub topic 13
Listing and Counting All Topological Orders
This chapter assumes you know Kahn's algorithm, recursion with backtracking, and bitwise operations on integers. Earlier chapters showed that a DAG can have many topological orders. Here you will list every one of them and count them without listing them.
Why You Would Want Every Order
Most of the time one valid order is enough. Sometimes you need all of them:
- Testing a scheduler against every legal execution order to find race-dependent bugs.
- Checking whether an order is unique. That happens when the count is exactly 1.
- Measuring how much freedom a plan has. A high count means many tasks are independent.
The number of orders can grow factorially. A graph with n nodes and no edges has n! orders, so listing them only works for small graphs.
Listing Orders with Backtracking
The idea extends Kahn's algorithm. At each step, any node with in-degree 0 that has not been placed is a legal next choice. Instead of picking one, try each in turn, recurse, then undo the choice.
def all_topo_orders(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
placed = set()
order = []
results = []
def backtrack():
if len(order) == len(indegree):
results.append(order.copy())
return
for u in indegree:
if indegree[u] == 0 and u not in placed:
placed.add(u)
order.append(u)
for v in graph.get(u, []):
indegree[v] -= 1
backtrack()
for v in graph.get(u, []):
indegree[v] += 1
order.pop()
placed.remove(u)
backtrack()
return results
print(all_topo_orders({"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}))
# [['a', 'b', 'c', 'd'], ['a', 'c', 'b', 'd']]If the graph has a cycle, the nodes on the cycle never reach in-degree 0. No branch completes, and the function returns an empty list.
Counting Without Listing
If you only need the count, you can avoid generating each order. Use dynamic programming over subsets. dp[mask] is the number of ways to order the set of nodes in mask as a valid prefix. A node i can extend mask if all of its predecessors are already in mask.
def count_topo_orders(graph):
nodes = list(graph)
index = {u: i for i, u in enumerate(nodes)}
pred = [0] * len(nodes)
for u in graph:
for v in graph[u]:
pred[index[v]] |= 1 << index[u]
n = len(nodes)
dp = [0] * (1 << n)
dp[0] = 1
for mask in range(1 << n):
if dp[mask] == 0:
continue
for i in range(n):
if not mask & (1 << i) and pred[i] & mask == pred[i]:
dp[mask | (1 << i)] += dp[mask]
return dp[(1 << n) - 1]
print(count_topo_orders({"a": ["c"], "b": ["c"], "c": [], "d": []}))
# 8Here c must follow both a and b, which gives 2 orders of those three nodes. Node d can go in any of 4 positions, so the total is 2 × 4 = 8.
Cost Comparison
| Method | Time | Practical limit |
|---|---|---|
| Backtracking enumeration | O(k · (V + E)) for *k* orders | *k* in the thousands to millions |
| Subset DP count | O(2^V · V) | about 20–25 nodes |
| Uniqueness check (Kahn) | O(V + E) | any size |
You don't need either method to test uniqueness. Run Kahn's algorithm and check that the queue never holds more than one node. Equivalently, every consecutive pair in the order must be joined by an edge.
Exercise
How many topological orders does a graph with three nodes x, y, z and no edges have? How many does it have after you add the single edge x -> y?
Show answer
With no edges, all 3! = 6 permutations are valid. With x -> y, exactly half of them put x before y, so 3 orders remain: x y z, x z y, z x y.
Exercise
The backtracking function returns an empty list for a graph. What does that tell you?
Show answer
The graph contains a cycle (or is otherwise impossible to complete), because no branch ever placed every node. A DAG always has at least one topological order.