Builds onGraph BFS and DFS
01The idea
A topological order lists the nodes of a directed graph so that every arrow points forward. If task a must finish before task b, then a comes before b in the order. Such an order exists only when the graph has no cycle. With a cycle, every task in it waits on another task in it, and none can go first.
The usual way to build one is Kahn's algorithm. It counts, for each node, how many arrows point into it. That count is the number of unfinished prerequisites.
- Every node with a count of 0 is ready. Put it in a queue or a list.
- Take a ready node and add it to the order. For each arrow out of it, lower the count of the node at the other end by one.
- When a count drops to 0, that node becomes ready.
- Repeat until nothing is ready.
If the order holds every node, you are done. If some nodes never became ready, they sit on a cycle.
You can also process the ready nodes in rounds, the way BFS processes levels. Each round takes everything that is ready right now. Then the number of rounds is the length of the longest chain of prerequisites.
02How to spot it
Use a topological sort when:
- the input lists dependencies, prerequisites or "a before b" rules
- the question asks for a valid order, or whether any order exists
- the question asks for the fewest rounds or semesters when ready tasks can run together
- you must detect a cycle in a directed graph
Watch the direction of each pair. "[a, b] means b depends on a" and "[a, b] means a depends on b" give opposite arrows. Read the problem statement carefully, and draw one example.
A depth-first search can also produce a topological order. Add each node to a list after all of its descendants are finished, then reverse the list. Kahn's algorithm is easier to get right and finds cycles for free.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue