Sub topic 12
Topological Sort of a DAG
Assume you know graph representations, queues, stacks, recursion, and asymptotic notation. This chapter uses directed graphs and focuses on directed acyclic graphs (DAGs).
What topological sort means
A topological order is a linear ordering of the vertices of a directed graph such that every edge points from an earlier vertex to a later vertex.
For an edge \(u \rightarrow v\), vertex \(u\) must appear before \(v\). This models prerequisites:
- A course must be completed before an advanced course.
- A source file must be compiled before a dependent file.
- A task must finish before the next task starts.
A topological order exists exactly when the graph is a DAG. A directed cycle makes the requirements impossible. For example, if \(A \rightarrow B\), \(B \rightarrow C\), and \(C \rightarrow A\), each vertex must come before another vertex in the same cycle.
For this graph, A, B, C, D and A, C, B, D are both valid orders.
Kahn’s algorithm
Kahn’s algorithm repeatedly removes a vertex with in-degree zero. The in-degree of a vertex is the number of edges entering it.
- Add every zero-in-degree vertex to a queue.
- Remove one vertex and append it to the order.
- Decrease the in-degree of each outgoing neighbour.
- Add any neighbour whose in-degree becomes zero.
- If fewer than \(V\) vertices were output, the graph contains a cycle.
from collections import deque
def topological_sort(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] += 1
ready = deque(u for u in graph if indegree[u] == 0)
order = []
while ready:
u = ready.popleft()
order.append(u)
for v in graph[u]:
indegree[v] -= 1
if indegree[v] == 0:
ready.append(v)
if len(order) != len(graph):
raise ValueError("graph contains a directed cycle")
return order
graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}
print(topological_sort(graph))With an adjacency list, the running time is \(O(V+E)\), and the extra space is \(O(V)\). The result need not be unique. Choosing a priority queue instead of a regular queue can produce the lexicographically smallest valid order.
DFS method and common errors
A depth-first search can also produce an order. After visiting all outgoing neighbours of a vertex, push that vertex onto a stack. Reversing the stack gives the topological order. DFS must track three states: unvisited, currently visiting, and finished. An edge to a currently visiting vertex identifies a cycle.
Common errors include treating an undirected cycle as the same as a directed cycle, forgetting disconnected vertices, and returning a partial order when a cycle exists.
Exercise
What should Kahn’s algorithm conclude if it processes only 4 of 5 vertices?
Show answer
The graph contains a directed cycle. At least one remaining vertex never reached in-degree zero.