A directed acyclic graph (DAG) represents dependencies: tasks that must be done before others, courses with prerequisites, modules that import each other. A topological order is a way to sort them respecting all dependencies. It exists if and only if there are no cycles.
import heapq
def topological_order(n, dependencies):
after = [[] for _ in range(n)]
pending = [0] * n
for a, b in dependencies: # a must be done before b
after[a].append(b)
pending[b] += 1
ready = [i for i in range(n) if pending[i] == 0]
heapq.heapify(ready)
order = []
while ready:
u = heapq.heappop(ready)
order.append(u)
for v in after[u]:
pending[v] -= 1
if pending[v] == 0:
heapq.heappush(ready, v)
return order if len(order) == n else None # None: there is a cycle
print(topological_order(4, [(0, 1), (0, 2), (1, 3), (2, 3)])) # [0, 1, 2, 3]
print(topological_order(3, [(0, 1), (1, 2), (2, 0)])) # None
- Kahn’s algorithm: start from the nodes with no pending dependencies; when you “do” one, one dependency is subtracted from its successors and those that reach zero become ready.
- If at the end not all nodes have been ordered, there is a cycle (none of the remaining ones can start).
- With a priority queue you get the lexicographically smallest order; with a normal queue, any valid one.
- It is what a package manager does when installing dependencies, or
makewhen deciding what to compile first.
You practice it in Topological order.