Topological Sort
Order the nodes of a directed graph so every edge points forward, detect cycles with Kahn's algorithm or DFS, and run DP over the order.
The problem
A DAG (directed acyclic graph) is a directed graph with no directed cycle. A topological order lists all nodes so that for every edge , comes before .
Everyday meaning: tasks with prerequisites, build steps that depend on each other, courses that need other courses. The order tells you what can be done first.
Two facts:
- A topological order exists if and only if the graph has no directed cycle.
- It is usually not unique. Independent nodes can appear in any relative order.
1 of 7