Sub topic 15
Strongly Connected Components
This chapter assumes you already know recursive DFS, finish order (post-order), the difference between back edges and cross edges, and topological sorting by reversing finish order. All the code is Python and uses the same adjacency-list dictionaries as earlier chapters.
What a Strongly Connected Component Is
In a directed graph, two vertices u and v are strongly connected when there is a path from u to v and also a path from v to u. This relation splits the vertices into groups. A strongly connected component (SCC) is a largest set of vertices in which every vertex can reach every other vertex.
In an undirected graph, connected components only need one path between two vertices, because every edge works in both directions. Directed graphs need paths both ways. One edge x -> y with no way back leaves x and y in different SCCs.
SCCs come up in practical problems:
- In a module dependency graph, an SCC with more than one module is a circular import cluster.
- In a call graph, an SCC is a set of mutually recursive functions.
- In 2-SAT solvers, a formula is unsatisfiable exactly when a variable and its negation fall in the same SCC.
- In web or social graphs, SCCs pick out tightly linked communities.
The Condensation Graph
Shrink each SCC to a single node and keep only the edges that run between different components. The result is the condensation, and it is always a directed acyclic graph (DAG). If two components could reach each other, they would be one component.
This chapter uses the following example graph throughout:
graph = {
"a": ["b"],
"b": ["c", "d"],
"c": ["a"],
"d": ["e"],
"e": ["f"],
"f": ["d"],
"g": ["f", "h"],
"h": ["g"],
}Its SCCs are {a, b, c}, {d, e, f}, and {g, h}.
Both algorithms below rely on the condensation being a DAG. Kosaraju's algorithm uses that fact explicitly. Tarjan's algorithm relies on it without saying so.
Kosaraju's Algorithm
Kosaraju's algorithm makes two DFS passes:
- Run a full DFS on the graph and record vertices in finish order.
- Build the transpose graph, which has every edge reversed.
- Go through the vertices in decreasing finish time. Each time you reach a vertex that is not yet assigned, run a DFS on the transpose graph from it. Every vertex that DFS reaches is one SCC.
def kosaraju(graph):
visited = set()
order = []
def visit(node):
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
visit(neighbor)
order.append(node) # finish order
for node in graph:
if node not in visited:
visit(node)
reverse = {node: [] for node in graph}
for node in graph:
for neighbor in graph[node]:
reverse[neighbor].append(node)
assigned = set()
components = []
def collect(node, component):
assigned.add(node)
component.append(node)
for neighbor in reverse[node]:
if neighbor not in assigned:
collect(neighbor, component)
for node in reversed(order):
if node not in assigned:
component = []
collect(node, component)
components.append(component)
return components
graph = {
"a": ["b"], "b": ["c", "d"], "c": ["a"],
"d": ["e"], "e": ["f"], "f": ["d"],
"g": ["f", "h"], "h": ["g"],
}
print(kosaraju(graph)) # [['g', 'h'], ['a', 'c', 'b'], ['d', 'f', 'e']]Why the Second Pass Stays Inside One Component
Take two SCCs C1 and C2 with an edge from C1 to C2. The latest finish time in C1 is always later than every finish time in C2. This holds whichever component DFS enters first. If DFS enters C1 first, it reaches all of C2 and finishes it before returning. If it enters C2 first, it cannot get back to C1 at all, so C1 starts and finishes later.
As a result, the vertex with the latest finish time belongs to a source component of the condensation. In the transpose graph that component becomes a sink, so a DFS started there cannot leave it. After you mark that component, the next unassigned vertex in finish order sits in a source component of what is left, and the same argument applies again.
In the example, the first pass gives the finish order c, f, e, d, b, a, h, g. The second pass starts at g, and in the transpose graph g reaches only h. Next comes a, which reaches c and b. Finally d reaches f and e. The edge from d back to b in the transpose graph is ignored because b is already assigned. Components come out in topological order of the condensation.
Tarjan's Algorithm
Tarjan's algorithm finds SCCs in a single DFS pass and never builds the transpose graph. It gives each vertex two numbers:
index[v]is the discovery counter, the order in which DFS first reachedv.low[v]is the smallest index reachable fromvthrough its DFS subtree plus at most one edge to a vertex still on the stack.
Vertices are pushed onto a separate stack when they are discovered. A vertex v with low[v] == index[v] is the root of an SCC. Everything above it on the stack, down to and including v, forms that component.
def tarjan(graph):
index = {}
low = {}
stack = []
on_stack = set()
components = []
counter = 0
def visit(node):
nonlocal counter
index[node] = low[node] = counter
counter += 1
stack.append(node)
on_stack.add(node)
for neighbor in graph[node]:
if neighbor not in index: # tree edge
visit(neighbor)
low[node] = min(low[node], low[neighbor])
elif neighbor in on_stack: # edge into the current SCC candidate
low[node] = min(low[node], index[neighbor])
# otherwise: edge into a finished SCC, ignore it
if low[node] == index[node]: # node is an SCC root
component = []
while True:
w = stack.pop()
on_stack.remove(w)
component.append(w)
if w == node:
break
components.append(component)
for node in graph:
if node not in index:
visit(node)
return components
graph = {
"a": ["b"], "b": ["c", "d"], "c": ["a"],
"d": ["e"], "e": ["f"], "f": ["d"],
"g": ["f", "h"], "h": ["g"],
}
print(tarjan(graph)) # [['f', 'e', 'd'], ['c', 'b', 'a'], ['h', 'g']]Tracing the Low-Link Values
| Vertex | index | final low | Event |
|---|---|---|---|
| a | 0 | 0 | Root of `{a, b, c}`, popped last |
| b | 1 | 0 | Gets low 0 from `c` |
| c | 2 | 0 | Edge `c -> a` reaches a vertex on the stack |
| d | 3 | 3 | `low == index`, so it pops `f, e, d` |
| e | 4 | 3 | Gets low 3 from `f` |
| f | 5 | 3 | Edge `f -> d` reaches a vertex on the stack |
| g | 6 | 6 | Edge `g -> f` is ignored, `f` is already popped |
| h | 7 | 6 | Edge `h -> g` reaches a vertex on the stack |
The edge g -> f is a cross edge into a component that has already been emitted. The on_stack check is there to ignore exactly this kind of edge. If you drop that check, low[g] becomes 3, g and h are never recognized as a root, and the output is wrong.
Tarjan emits components in reverse topological order of the condensation: sinks come first. Kosaraju emits them in topological order. If you need a specific order, for example for 2-SAT assignment, keep track of which algorithm you used.
Choosing Between Them
| Concern | Kosaraju | Tarjan |
|---|---|---|
| DFS passes | Two | One |
| Extra memory | Transpose graph, O(V + E) | Index, low, and stack, O(V) |
| Output order | Topological | Reverse topological |
| Ease of getting it right | Easy, just two plain DFS runs | Low-link updates are easy to get wrong |
| Time | O(V + E) | O(V + E) |
Both algorithms touch each vertex and each edge a constant number of times. Tarjan usually runs faster in practice because it skips building the transpose graph. Kosaraju is easier to explain and debug.
Edge Cases
- Single vertices: A vertex that is not on any cycle is its own SCC of size one. Both algorithms report it. If you are looking for circular dependencies, filter for components of size greater than one, or size one with a self-loop.
- Self-loops: An edge
v -> vdoes not change the result. In Tarjan, it setslow[v] = index[v], which has no effect. - Vertices that appear only as targets: Both functions assume every vertex is a key in
graph. Add missing vertices with empty lists before you call them. - Parallel edges: Duplicate edges do no harm and only add to the E term.
Exercise
Add the edge "f": ["d", "a"] to the example graph. What are the SCCs now, and why?
Show answer
There are two SCCs: {a, b, c, d, e, f} and {g, h}. Before the change, a reached d through b -> d. Now f -> a gives a path from d back to a (d -> e -> f -> a), so the two old cycles merge into one component. The vertices g and h can reach f but nothing reaches g or h from the merged set, so {g, h} stays separate.
Exercise
In Kosaraju's algorithm, what goes wrong if the second pass visits vertices in increasing finish order instead of decreasing?
Show answer
The first vertex then tends to come from a sink component of the original graph, which is a source component in the transpose graph. A DFS from a source in the transpose graph can reach other components. With the example graph, starting at c in the transpose graph reaches b, a, and then nothing else, which is fine by luck. Starting at f reaches e, d, b, c, a, and g, h, which wrongly merges three SCCs.
Exercise
Write a function that uses tarjan() to return True when a directed graph contains a cycle. Count self-loops as cycles.
Show answer
def hascyclescc(graph): for component in tarjan(graph): if len(component) > 1: return True v = component[0] if v in graph[v]: return True return False A cycle exists exactly when some SCC has more than one vertex, or when a single vertex has an edge to itself.