Memra

Topological sort & strongly connected components

◈ 7 cards

Order 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:

  1. Run DFS to compute finish times .
  2. As each vertex finishes, push it onto the front of a list.
  3. 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, :

  1. Run DFS to compute finish times .
  2. Compute .
  3. Run DFS, starting vertices in decreasing order from step 1.
  4. 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.

undershorts#2pants#6belt#8shirt#4tie#5jacket#9Every edge points from a smaller # to a larger one.
The # is the vertex’s place in the nine-item order the exercise prints (watch #1, socks #3 and shoes #7 are off-figure). Decreasing finish time produced that order; an arrow pointing from a higher # back to a lower one would be a back edge — a cycle — and no topological order would exist.
a,b,epeeled 1stc,d2ndf,g3rdh4thContracting every SCC always leaves a DAG.
The four SCCs {a,b,e}, {c,d}, {f,g} and {h} contracted to points. Contracting always leaves a DAG — a cycle between two components would make them mutually reachable, i.e. one component. Running the second DFS on Gᵀ in decreasing finish order peels them in exactly this left-to-right order.
NORMAL ~/memra/learn/comp-372/topological-sort-scc utf-8 LF