ABDCEF1def scc(g):2 order = finish_order(g)3 rg = reverse(g)4 seen, comps = set(), []5 for v in reversed(order):6 if v not in seen:7 c = walk(rg, v, seen)8 comps.append(c)9 return compsorder: the finish list[0][1][2][3][4][5]E
Pucks: nodes; ink arrows: one-way edgesLime walker: the depth-first search; chips: nodes entering or leaving the order listIslands: one strongly connected component eachKosaraju's algorithm on a six-node directed graph. Pass 1: a depth-first search lists the nodes in the order they finish (E, D, C, B, A, F). Then every arrow is reversed. Pass 2: searches start from the end of the list; each one stays inside a single strongly connected component and lifts its island: {F}, {A, B}, {C, E, D}.

Strongly connected

  1. A directed graph has nodes joined by one-way arrows. In Python we store it as a dict: each node lists the nodes its arrows point to. This one has six nodes and seven arrows.

Pass 1: finish order

Pass 2: flipped arrows

What happens

;; step 1/11 · graph
g = {
  'A': ['B'],
  'B': ['A', 'C'],
  'C': ['D'],
  'D': ['E'],
  'E': ['C'],
  'F': ['E'],
}

6 nodes, 7 arrows: A→B  B→A  B→C  C→D  D→E  E→C  F→E

Why it works: the node that finishes last in pass 1 lies in a component that no arrow from another component enters. After flipping, no arrow leaves that component, so the pass 2 search from it stays inside. Once that component is marked seen, the same holds for the next one. This is Kosaraju's algorithm in the form CLRS gives it: finish order on the graph, then searches on the reversed graph. Sedgewick and Wayne run the mirror image (finish order on the reversed graph, then searches on the original). Both find the same components.