Topological sort & strongly connected components
◈ 7 cardsOrder a DAG by decreasing DFS finish time; find SCCs with DFS, transpose, DFS in finish order.
Topological sort
A topological sort of a DAG is a linear order of all vertices such that every edge has before . It exists iff is a DAG (no directed cycle). The CLRS algorithm is a one-liner on top of DFS:
- Run DFS to compute finish times .
- As each vertex finishes, push it onto the front of a list.
- Return the list.
That returns vertices in decreasing finish time. Why it works: for any DAG edge , DFS gives (Theorem 20.12) — when is explored, is never gray (that would be a back edge, hence a cycle), so is white-then-finishes-before-, or already black with a smaller finish. Ordering by decreasing therefore places before for every edge. Running time: , same as DFS.
Alternative — Kahn's in-degree method. Repeatedly remove a vertex of in-degree 0 and decrement its neighbours' in-degrees, using a queue. Also ; if fewer than vertices come out, the graph had a cycle.
Worked example. On the “getting dressed” DAG (undershorts before pants, pants before belt and shoes, shirt before belt and tie, belt and tie before jacket, socks before shoes), DFS-by-finish-time yields a valid dressing order such as watch undershorts socks shirt tie pants shoes belt jacket — every prerequisite precedes what depends on it.
Strongly connected components
An SCC of a directed graph is a maximal set where every pair is mutually reachable ( and ). The transpose reverses every edge; and have the same SCCs. Contracting each SCC to a point gives the component graph, which is always a DAG.
Kosaraju's algorithm (CLRS 20.5) — four steps, :
- Run DFS to compute finish times .
- Compute .
- Run DFS, starting vertices in decreasing order from step 1.
- Each tree of that second forest is one SCC.
Why it works: the SCC with the largest finish time is a source in the component DAG, so in it is a sink — the second DFS, started there, can reach exactly that SCC and no further (Corollary 20.15 + the white-path theorem). Peeling SCCs in decreasing-finish order isolates one component per tree.