Sub topic 13
Strongly Connected Components as Cyclic Regions
Three-color DFS and Kahn's algorithm each answer one question: does this directed graph contain a cycle? A real dependency graph with a problem often has several tangles, and fixing one cycle may leave others in place. Strongly connected components (SCCs) report every cyclic region in one O(V + E) pass and tell you exactly which vertices belong to each one.
This chapter assumes you know three-color DFS from the chapter on directed graphs, Kahn's algorithm, and the explicit-stack style of iterative DFS covered earlier.
What a Strongly Connected Component Is
Two vertices u and v are strongly connected when there is a directed path from u to v and another from v to u. This relation is an equivalence relation:
- It is reflexive, because every vertex reaches itself by the empty path.
- It is symmetric by definition.
- It is transitive, because paths can be joined end to end.
The relation therefore splits the vertices into disjoint classes. Each class is a strongly connected component, which is a maximal set of vertices where every vertex can reach every other.
The link to cycles is direct. If u and v are different vertices in the same SCC, the path from u to v followed by the path from v to u is a closed walk, and every closed walk contains a cycle. In the other direction, all vertices on a cycle can reach each other, so the whole cycle lies inside one SCC. This gives the central fact of the chapter:
The self-loop case is the usual trap. A vertex with an edge to itself forms an SCC of size 1, so a check of len(component) > 1 alone misses it.
The Condensation Is Always a DAG
Collapse each SCC into a single node and keep an edge from component A to component B whenever some original edge goes from a vertex in A to a vertex in B. The result is called the condensation, and it never has a cycle. Suppose it had a cycle through components A and B. Then every vertex of A could reach every vertex of B and the reverse, so A and B would form one component, which contradicts maximality.
This splits the graph into two parts. The cyclic structure lies entirely inside components, and the structure between components is a DAG that you can sort topologically.
Tarjan's Algorithm
Tarjan's algorithm finds all SCCs with one DFS. Each vertex gets two numbers:
index[u]is the order in which DFS discovered u.low[u]is the smallest index reachable from u's DFS subtree using tree edges plus at most one edge to a vertex still on the algorithm's stack.
Vertices are pushed onto a separate stack when they are discovered. When DFS finishes a vertex u and low[u] == index[u], u is the root of an SCC. Everything above u on the stack, with u itself, forms that component, and those vertices are popped together.
The on_stack test matters. An edge into a vertex that has already been assigned to a finished component is a cross edge into a different SCC, and it must not lower low[u]. This matches the gray-vertex idea from three-color DFS. Only edges back into the region still in progress can close a cycle.
The version below is iterative so that long dependency chains do not hit Python's recursion limit:
def tarjan_scc(adj):
n = len(adj)
index = [-1] * n
low = [0] * n
on_stack = [False] * n
stack = []
sccs = []
counter = 0
for s in range(n):
if index[s] != -1:
continue
index[s] = low[s] = counter
counter += 1
stack.append(s)
on_stack[s] = True
work = [(s, iter(adj[s]))]
while work:
u, it = work[-1]
v = next(it, None)
if v is None:
work.pop()
if work:
p = work[-1][0]
low[p] = min(low[p], low[u])
if low[u] == index[u]:
component = []
while True:
w = stack.pop()
on_stack[w] = False
component.append(w)
if w == u:
break
sccs.append(component)
elif index[v] == -1:
index[v] = low[v] = counter
counter += 1
stack.append(v)
on_stack[v] = True
work.append((v, iter(adj[v])))
elif on_stack[v]:
low[u] = min(low[u], index[v])
return sccs
def cyclic_regions(adj):
regions = []
for comp in tarjan_scc(adj):
if len(comp) > 1 or comp[0] in adj[comp[0]]:
regions.append(sorted(comp))
return regions
adj = [[1], [2], [0, 3], [4], [3, 5], [5, 6], []]
print(tarjan_scc(adj))
print(cyclic_regions(adj))Output:
[[6], [5], [4, 3], [2, 1, 0]]
[[5], [3, 4], [0, 1, 2]]Tarjan emits components in reverse topological order of the condensation: sinks come first. In this run, {6} appears before {5}, and {0,1,2} appears last. If you need the components in dependency order, for example to build components in a valid sequence, reverse the list.
Tracing the Example
| Step | Event | Effect |
|---|---|---|
| 1 | DFS goes 0 → 1 → 2 | index 0, 1, 2 |
| 2 | Edge 2 → 0, and 0 is on the stack | low[2] = 0 |
| 3 | DFS goes 2 → 3 → 4 | index 3, 4 |
| 4 | Edge 4 → 3, and 3 is on the stack | low[4] = 3 |
| 5 | DFS goes 4 → 5, and 5 → 5 is a self-loop | low[5] stays 5 |
| 6 | DFS goes 5 → 6, then 6 finishes | low[6] = index[6], emit {6} |
| 7 | 5 finishes | low[5] = index[5], emit {5} |
| 8 | 4 finishes, then 3 finishes | low[3] = index[3], emit {4, 3} |
| 9 | 2, 1, 0 finish | low[0] = index[0], emit {2, 1, 0} |
The self-loop at step 5 compares index[5] with itself, so it cannot change low[5]. That is why cyclic_regions checks for self-loops separately.
Building the Condensation
Once each vertex has a component id, building the condensation takes one more pass over the edges:
def condensation(adj):
sccs = tarjan_scc(adj)
comp_id = [0] * len(adj)
for cid, comp in enumerate(sccs):
for v in comp:
comp_id[v] = cid
dag = [set() for _ in sccs]
for u in range(len(adj)):
for v in adj[u]:
if comp_id[u] != comp_id[v]:
dag[comp_id[u]].add(comp_id[v])
return sccs, comp_id, [sorted(s) for s in dag]
adj = [[1], [2], [0, 3], [4], [3, 5], [5, 6], []]
sccs, comp_id, dag = condensation(adj)
print(comp_id)
print(dag)Output:
[3, 3, 3, 2, 2, 1, 0]
[[], [0], [1], [2]]Using sets removes the parallel edges that appear when several original edges connect the same pair of components.
How SCCs Compare with the Other Directed Methods
The three directed methods report different amounts of information. The example graph shows the difference clearly.
| Method | What it reports | Result on the example |
|---|---|---|
| Three-color DFS | Whether a cycle exists, and optionally one cycle | One cycle, such as 0 → 1 → 2 → 0 |
| Kahn's algorithm | Vertices that never reach in-degree 0 | All 7 vertices, including 6 |
| Tarjan SCC | Every cyclic region and its exact members | {0,1,2}, {3,4}, {5} |
Kahn's leftover set is the weakest diagnostic here. Vertex 6 lies on no cycle, but it sits downstream of cycles, so its in-degree never drops to zero. Kahn's algorithm cannot tell "on a cycle" apart from "blocked by a cycle." SCCs make that distinction, so they are the right tool when you have to show a user what to fix.
Gotchas and Edge Cases
- Self-loops. These form single-vertex cyclic SCCs, as shown above. Check for them explicitly.
- Parallel edges. They do not change the components. They only produce duplicate edges in the condensation, which a set removes.
- Disconnected graphs. The outer loop over every start vertex covers all of them, just as it does in three-color DFS.
- Undirected graphs. SCCs add nothing here. Every connected component is trivially strongly connected, because each edge works in both directions. For undirected cycles, use the parent-edge DFS or union-find methods from earlier chapters, or look at biconnected components.
- An SCC is not a cycle. A component can contain many overlapping cycles, and there may be no single simple cycle that passes through all of its vertices. To report one concrete cycle, run the reconstruction method from the earlier chapter on the subgraph induced by that component.
- Kosaraju's algorithm. This alternative runs two DFS passes, one on the graph and one on its reverse, and needs the reversed adjacency list in memory. It has the same O(V + E) cost. Tarjan's single pass usually uses less memory, and Kosaraju is often easier to get right on the first try.
When to Reach for SCCs
Use SCCs when the answer must cover every cycle at once. Typical cases are a package manager that lists every circular dependency group, a build system that refuses to proceed and names every module involved, or a deadlock detector that reports every group of threads waiting on each other. If you only need a yes-or-no answer, three-color DFS or Kahn's algorithm is simpler and runs at the same asymptotic cost.
Exercise
A directed graph has 5 vertices with edges 0→1, 1→2, 2→3, 3→1, 3→4, and 4→4. List its SCCs, say which ones are cyclic, and say which vertices Kahn's algorithm would leave unremoved.
Show answer
The SCCs are {0}, {1,2,3}, and {4}. {1,2,3} is cyclic because it has more than one vertex. {4} is cyclic because of its self-loop. {0} is acyclic. Kahn's algorithm removes only vertex 0, which has in-degree 0. Vertices 1, 2, 3, and 4 are never removed, because 1 keeps an incoming edge from 3 and 4 keeps its self-loop.
Exercise
In tarjanscc, what goes wrong if the branch `elif onstack[v]: is changed to else:`, so that every already-visited neighbor lowers low[u]?
Show answer
Edges into vertices that already belong to a finished component would lower low[u] as well. Those are cross edges into a different SCC. Then low[u] could drop below index[u] even though u is a component root, the root test would fail, and separate SCCs would be merged. For example, add a vertex 7 with the edge 7→6 to the chapter's graph. If 7 is visited after 6 has been emitted, 7 would get low[7] = index[6] < index[7] and would never be emitted as its own component.
Exercise
Why does cyclic_regions need the test comp[0] in adj[comp[0]] only for single-vertex components?
Show answer
Any component with two or more vertices already contains a cycle, whether or not it has self-loops. A single vertex is cyclic only when it has an edge to itself, and Tarjan's algorithm alone does not mark that case, because a self-loop compares index[u] with itself and never changes low[u].