Strongly connected components: Kosaraju and Tarjan
Which vertices can reach one another by following arrows? Find strongly connected components with two algorithms: Kosaraju reverses edges between passes, while Tarjan extracts components during one DFS.
Video walkthrough
The vertical Rutube video is awaiting moderation. YouTube has both formats; the horizontal Rutube video is available.
Mutual reachability, not just a connection
A strongly connected component (SCC) is a maximal set in which every vertex can reach every other vertex by directed paths. Maximal matters: a mutually reachable subset of a larger SCC is not a separate component. SCCs are disjoint and cover every vertex.
Arrow directions matter: A → B does not provide a return path. An isolated vertex is an SCC of its own; a length-zero path connects it to itself, so no self-loop is required. Every SCC in a DAG is a singleton. The empty graph has the empty partition.
One partition, different reporting orders
In the default graph, A → B → C → A, D ↔ E and F ↔ G form three SCCs: {A, B, C}, {D, E}, {F, G}. C → D and E → F connect them. These links allow forward travel but no return, so the seven vertices are not a single SCC. Add F → B and the return path merges all three. Select “One edge merges all SCCs” to see this change.
With our traversal order, Kosaraju reports {A, B, C}, then {D, E}, then {F, G}; Tarjan reports the reverse order. Compare partitions without considering component order or vertex order inside each component. Completed SCCs receive display labels and colors based on their smallest vertex: C:A denotes a component whose smallest vertex is A. This display label is not a discovery number.
Kosaraju: finish order and reversed arrows
Pass 1 runs a full DFS on the original graph G. Append a vertex to finish order only after inspecting all its outgoing edges. The default graph finishes G, F, E, D, C, B, A. Pass 2 uses the transpose Gᵀ, replacing each A → B by B → A. Start roots in reverse finish order from pass 1, skipping vertices already visited in pass 2.
Transposition preserves SCCs: reverse every path inside a component and mutual reachability remains. For an edge C → D between distinct components, the largest finish time in C exceeds that in D. Thus pass 2 begins with a source component of the original graph among the unassigned components; in Gᵀ it cannot reach another unassigned component. Each new DFS in pass 2 collects exactly one SCC. Starting with Gᵀ and finishing with G is also correct, but changes the reporting order; this demo consistently uses G followed by Gᵀ.
Tarjan: index, low-link and two separate stacks
On entry, assign v a unique index[v] starting at zero, and set low[v] = index[v]. Push v onto S, the stack of visited vertices not yet assigned to completed SCCs. The current DFS path is stored separately. Returning from a DFS call does not remove its vertex from S: it may wait for its component root while DFS explores another branch.
In this version, low[v] is the smallest discovery index reachable from v through zero or more DFS tree edges followed by at most one edge to a vertex still on S. It is not the smallest index reachable by an arbitrary path. While only some edges have been processed, low reflects the explored portion. The “Finished DFS, still on S” example makes the distinction visible.
Three cases for an edge v → w
If w is unvisited, run DFS(w), then update low[v] = min(low[v], low[w]) on return. If w was visited and is still on S, use index[w], specifically: low[v] = min(low[v], index[w]). If w has already been popped and assigned to a completed SCC, this edge does not change low[v]. Testing only whether w was visited is insufficient.
For A → B, B → A, A → C, C → B, DFS has already returned from B when C inspects its edge to B. However, B is still on S. We obtain index(C) = 2 and low(C) = 1, although C can reach A with index 0 through B. A, B and C are still extracted together correctly. “Edge to a closed SCC” shows the opposite case: {A, B} has already been extracted, so C → A must not lower low(C).
When a component can be extracted
After inspecting every outgoing edge of v, compare low[v] with index[v]. Equality identifies the root of an unresolved SCC. Pop vertices from the top of S through v, inclusive: they form one component. The demo extracts this whole suffix in one event and shows its members. If low[v] < index[v], finish the DFS frame but keep v on S.
S contains exactly the visited vertices not yet assigned to a completed SCC. Every vertex is pushed once and popped once. The outer loop starts DFS from every unvisited vertex, covering disconnected parts and isolated vertices too. A self-loop does not merge its vertex with another component.
Condensation connects SCCs to topological sorting
Contract each SCC to one vertex, retain edges between distinct components and remove duplicates. The resulting condensation is a DAG. A cycle between its component vertices would make all those components mutually reachable, so they should have been one SCC.
The default condensation has edges A → D and D → F, where letters label SCCs rather than individual original vertices. The player lists these edges at completion. Condensation admits a topological order even when the original graph has cycles. The partition helps inspect circular dependencies; it does not remove those dependencies by itself.
Linear search and the cost of visualization history
With adjacency lists, both searches take O(V + E) time. Kosaraju runs two DFS passes and builds Gᵀ; explicitly storing reverse lists requires O(V + E) extra memory. Tarjan uses one DFS; its indices, low values, onStack flags and two stacks use O(V) beyond ready-made adjacency lists. Our input is an edge list, so input validation, a copy and building forward adjacency lists also require O(V + E).
The player counts only DFS edge inspections: 2E for Kosaraju and E for Tarjan, excluding transpose construction and input validation. Event counts and animation ticks do not measure runtime. Seeking requires independent O(V) snapshots at O(V + E) events: history costs O(V(V + E)) memory beyond the graph. The editor therefore accepts 0–8 vertices and at most 18 distinct edges.
Code matching the demo’s traversal order
Code vertices are 0…n−1, corresponding to A…H in the player. Neighbors follow edge input order. The snippets assume valid input; the editor separately checks limits, endpoints and duplicate edges. Kosaraju uses explicit DFS frames. Tarjan is recursive here for brevity; the player expands the same entries, returns and extractions into explicit frames while retaining a separate S.
Both functions return arrays of components in reporting order without storing history. Do not assume the recursive JavaScript snippet handles arbitrarily deep graphs: call-stack limits depend on the environment. Exhaustive small graphs and an independent mutual-reachability oracle check both snippets against the player model.
Kosaraju
function kosaraju(n, edges) {
const g = Array.from({length: n}, () => []);
const reversed = Array.from({length: n}, () => []);
for (const [a, b] of edges) { g[a].push(b); reversed[b].push(a); }
const seen = Array(n).fill(false), finish = [], groups = [];
function visit(root, graph, onFinish, onEnter) {
seen[root] = true; onEnter(root);
const frames = [{v: root, next: 0}];
while (frames.length) {
const f = frames[frames.length - 1];
if (f.next < graph[f.v].length) {
const w = graph[f.v][f.next++];
if (!seen[w]) {
seen[w] = true; onEnter(w);
frames.push({v: w, next: 0});
}
} else { onFinish(f.v); frames.pop(); }
}
}
for (let v = 0; v < n; v++)
if (!seen[v]) visit(v, g, v => finish.push(v), () => {});
seen.fill(false);
for (let i = finish.length - 1; i >= 0; i--) {
const v = finish[i];
if (seen[v]) continue;
const group = [];
visit(v, reversed, () => {}, w => group.push(w));
groups.push(group);
}
return groups;
}Tarjan
function tarjan(n, edges) {
const g = Array.from({length: n}, () => []);
for (const [a, b] of edges) g[a].push(b);
const index = Array(n).fill(-1), low = Array(n).fill(-1);
const onStack = Array(n).fill(false), stack = [], groups = [];
let clock = 0;
function dfs(v) {
index[v] = low[v] = clock++;
stack.push(v); onStack[v] = true;
for (const w of g[v]) {
if (index[w] === -1) {
dfs(w);
low[v] = Math.min(low[v], low[w]);
} else if (onStack[w]) {
low[v] = Math.min(low[v], index[w]);
} // A vertex assigned to a completed SCC does not affect low[v].
}
if (low[v] === index[v]) {
const group = [];
let w;
do {
w = stack.pop(); onStack[w] = false; group.push(w);
} while (w !== v);
groups.push(group);
}
}
for (let v = 0; v < n; v++) if (index[v] === -1) dfs(v);
return groups;
}CMU — Depth First Search and Strong Components · CP-Algorithms — SCC and condensation