Topological Sort
Imagine a city map where every road is one-way, and there are no circular routes. This is a Directed Acyclic Graph (DAG) (stored as a graph). You want to list all the cities in an order such that every one-way road goes from an earlier city to a later one in your list.
That ordering is called a topological sort. It's the answer to: "What's a valid order to do things when some tasks must come before others?" — like course prerequisites, build dependencies, or assembly steps.
Kahn's Algorithm (BFS-based)
The key insight: a city with no incoming roads (in-degree = 0) can go first — nothing needs to happen before it. Remove it, and some neighbors may now have no incoming roads either. Repeat.
DFS-based Algorithm
Run DFS. When a city is fully explored (all its outgoing roads have been followed), push it onto a stack. At the end, pop the stack to get the topological order. Cities finished last go to the front — they have no dependencies after them.
Cycle detection bonus
Kahn's algorithm doubles as a cycle detector: if the output has fewer than V cities, some cities had non-zero in-degree even after processing everything reachable — they're part of a cycle, making topological sort impossible.
← → arrow keys to step · click elements to interact