Topological Sort
Order vertices of a directed acyclic graph so every edge goes from earlier to later in the ordering.
The Mathematics
DAG ordering, DFS finish times, and correctness
DAG & Topological Order
A Directed Acyclic Graph (DAG) is a directed graph with no cycles. A topological ordering is a linear ordering of vertices such that:
A topological order exists if and only if the graph is a DAG. A DAG with vertices may have many valid orderings.
DFS Finish-Time Ordering
DFS assigns each node a finish time — when all descendants have been explored. The key insight:
Sorting by decreasing finish time gives a valid topological order. Equivalently, push to a stack on finish and reverse:
Complexity
DFS visits every vertex and edge exactly once:
Common Application
Course scheduling: if course A is a prerequisite of course B, then edge ensures A is scheduled before B. The topological sort gives a valid course sequence.
See It Work
DFS-based topological sort on a course-prerequisite DAG
Initialize: no nodes visited. We will DFS from each unvisited node.
The Code
Bridge from DFS finish-time ordering to Python implementation
Mathematical Formulation
Track which nodes have been fully processed
Stack collects nodes in reverse topological order
Mark node as visited when DFS enters it
For each edge, recurse on unvisited neighbors
Push node to stack when all descendants are processed (finish time)
Reversing finish-time order gives valid topological ordering
Python Implementation
def topological_sort(graph):
visited = set()
stack = []
def dfs(node):
visited.add(node) # Mark as visited
for neighbor in graph[node]: # Visit all neighbors
if neighbor not in visited:
dfs(neighbor) # Recurse on unvisited
stack.append(node) # Push after all descendants done
for node in graph: # Process all components
if node not in visited:
dfs(node)
return stack[::-1] # Reverse = topological order