Sub topic 5
Collapsing Components: The Condensation DAG
This chapter assumes you already know what a strongly connected component (SCC) is. It also assumes you can read adjacency lists in Python and can run a basic graph traversal. Here we take a graph's SCCs and shrink each one to a single node. The result is called the condensation. It is always a directed acyclic graph (DAG), and the algorithms later in this tutorial depend on that fact.
The Idea: One Node per Component
Take a directed graph G and split its vertices into SCCs C₁, C₂, …, Cₖ. The condensation of G, written G^SCC, is a new directed graph defined as follows:
- It has one vertex for each component Cᵢ.
- It has an edge Cᵢ → Cⱼ, with i ≠ j, whenever G has at least one edge u → v where u is in Cᵢ and v is in Cⱼ.
Edges that stay inside a single component vanish. Several edges between the same pair of components merge into one condensation edge.
Here is the running example for this chapter. It has 8 vertices and three components: A = {0, 1, 2}, B = {3, 4, 5}, and C = {6, 7}.
Only two edges cross component boundaries: 2 → 3 and 6 → 5. The condensation therefore has three nodes and two edges.
Why the Condensation Is Always Acyclic
Claim: G^SCC never contains a directed cycle.
Proof. Suppose the condensation had a cycle Cᵢ → Cⱼ → … → Cᵢ with Cᵢ ≠ Cⱼ. Pick any u in Cᵢ and any v in Cⱼ. Each condensation edge comes from a real edge in G, and any vertex of a component can reach any other vertex of the same component. That lets you chain the pieces together. Following the cycle forward from u gives a path u ⇝ v in G. Continuing around the cycle back to Cᵢ gives a path v ⇝ u. So u and v reach each other, and by definition they belong to the same SCC. That contradicts Cᵢ ≠ Cⱼ. ∎
The argument also shows that SCCs are maximal. If the condensation had a cycle, the components on it would merge into one larger component, so they could not have been separate SCCs in the first place.
What the Condensation Preserves
The condensation throws away detail inside components but keeps the information that matters across them.
| Property in G | Equivalent property in G^SCC |
|---|---|
| u can reach v | comp(u) = comp(v), or comp(u) can reach comp(v) |
| G contains a cycle | Some component has more than one vertex, or some vertex has a self-loop |
| G is strongly connected | G^SCC has exactly one node |
| G is already a DAG | G^SCC is isomorphic to G, with every component a single vertex |
The first row is the one you will use most. Reachability questions about G turn into reachability questions about a DAG, and DAGs are much easier to work with. You can topologically sort them, run dynamic programming over them, and find their sources and sinks.
Sources (components with in-degree 0) and sinks (components with out-degree 0) carry structural meaning. In the example, A and C are sources and B is the only sink. If you start a traversal anywhere in a sink component, it can never leave that component. Kosaraju's algorithm relies on this property, as you will see two chapters from now.
Building the Condensation in Code
Building the condensation needs a component label comp[u] for every vertex. Kosaraju's and Tarjan's algorithms compute these labels in linear time, and later chapters cover both. To keep this chapter self-contained, the code below uses a slow but obviously correct labeler. It runs one reachability search from every vertex, and two vertices share a label exactly when each reaches the other. That costs O(V·(V + E)), which is fine for small test graphs and useful as a reference when you test the faster algorithms.
from collections import deque
def reach(n, adj, s):
"""Return a list seen[] where seen[v] is True if s can reach v."""
seen = [False] * n
seen[s] = True
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if not seen[v]:
seen[v] = True
stack.append(v)
return seen
def scc_labels_bruteforce(n, adj):
"""Label SCCs by mutual reachability. O(V * (V + E)): reference use only."""
R = [reach(n, adj, s) for s in range(n)]
comp = [-1] * n
c = 0
for u in range(n):
if comp[u] == -1:
for v in range(n):
if R[u][v] and R[v][u]:
comp[v] = c
c += 1
return comp
def condensation(n, adj, comp):
"""Build the component DAG as a list of sets of successor component ids."""
k = max(comp, default=-1) + 1
dag = [set() for _ in range(k)]
for u in range(n):
for v in adj[u]:
if comp[u] != comp[v]: # drop edges inside a component
dag[comp[u]].add(comp[v]) # set removes duplicate edges
return dag
def topo_order(dag):
"""Kahn's algorithm. Returns an order, or raises if there is a cycle."""
k = len(dag)
indeg = [0] * k
for a in range(k):
for b in dag[a]:
indeg[b] += 1
q = deque(i for i in range(k) if indeg[i] == 0)
order = []
while q:
a = q.popleft()
order.append(a)
for b in sorted(dag[a]):
indeg[b] -= 1
if indeg[b] == 0:
q.append(b)
if len(order) != k:
raise ValueError("condensation has a cycle: labels are wrong")
return order
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
n = len(adj)
comp = scc_labels_bruteforce(n, adj)
dag = condensation(n, adj, comp)
print(comp) # [0, 0, 0, 1, 1, 1, 2, 2]
print(dag) # [{1}, set(), {1}]
print(topo_order(dag)) # [0, 2, 1]
sizes = [comp.count(c) for c in range(len(dag))]
print(sizes) # [3, 3, 2]condensation runs in O(V + E) time once the labels exist, because it looks at each edge once and each set insertion takes expected constant time. The topo_order check is a cheap sanity test. A labeling that produces a cyclic "condensation" has merged too little, meaning two components that should be one were kept apart.
Component Numbering Is Not Standardized
The condensation is defined up to the names of its nodes. Different SCC algorithms assign component ids in different orders:
- The brute-force labeler above numbers components by their smallest vertex. That order has no topological meaning.
- Kosaraju's algorithm, as written later in this tutorial, numbers components in a topological order of the condensation.
- Tarjan's algorithm emits components in reverse topological order.
Never assume comp[u] < comp[v] implies anything about edge direction unless you know which algorithm produced the labels and how it numbers them. If later code needs a topological order, compute one explicitly, or document the guarantee you are relying on.
Edge Cases and Common Mistakes
Other cases to handle deliberately:
- Parallel edges. If you store successors in lists instead of sets, five edges from A to B become five condensation edges. Some algorithms tolerate that. Anything that counts in-degrees or edges does not. Deduplicate, or store edge multiplicities on purpose if you need them (for example, to weight dependencies).
- Self-loops in G. A self-loop u → u never crosses a component boundary, so it never appears in the condensation. It does matter for cycle detection, though. A single-vertex component with a self-loop is a cycle, and one without a self-loop is not.
- Isolated vertices. A vertex with no edges is its own component and must still appear as a condensation node. Size the DAG from the number of components, not from the edges you see.
- Empty graph. With n = 0,
max(comp, default=-1)gives k = 0 and an empty DAG. Without thedefault,maxraises an error. - Memory. A list of sets costs more than a list of lists. On large graphs, a common alternative is to collect
(comp[u], comp[v])pairs, sort them, and remove consecutive duplicates. That uses O(E) memory with small constants, plus O(E log E) time for the sort.
Exercise
A directed graph has edges 0→1, 1→0, 1→2, 2→3, 3→2, 3→4, and 4→4. List its SCCs, then give the condensation's nodes and edges. Which components are sources and which are sinks?
Show answer
The SCCs are {0,1}, {2,3}, and {4}. The edges 1→2 and 3→4 cross components, so the condensation is {0,1} → {2,3} → {4}. The self-loop 4→4 stays inside {4} and is dropped. {0,1} is the only source and {4} is the only sink.
Exercise
Someone builds a condensation and finds that Kahn's algorithm processes only 4 of its 6 nodes. Assuming the condensation code is correct, what does this tell you about the component labels?
Show answer
The condensation contains a cycle, which is impossible for a true SCC partition. So the labeling split at least one real SCC into several labels. Components on that cycle reach each other and should have shared one label. In other words, the labeler under-merged.
Exercise
Explain why u can reach v in G exactly when comp(u) = comp(v) or comp(u) can reach comp(v) in the condensation.
Show answer
Any path in G maps to a walk in the condensation: steps inside a component disappear, and steps between components become condensation edges. So reachability in G implies the condition. In the other direction, each condensation edge comes from a real edge x→y in G, and inside each component any vertex reaches any other. You can therefore stitch a real path from u to v by moving within each component to the endpoint of the next crossing edge, crossing it, and repeating.