GraphsAnimated
Topological Sorting
Order a DAG so every edge points forward.
Time
O(V + E)
Extra space
O(V)
Use it for
Build order, course prerequisites.
How it works
- A topological order lists every node before the nodes it points to (think: courses before the courses that need them). It exists only if there is no cycle.
- Run a depth-first search. When a node has no unvisited neighbours left, it is finished: push it onto a stack.
- The finishing order, reversed, is a valid topological order.
- O(V + E).
Watch it run
Loading animation…