Sub topic 16
More Applications: Cycles, Dependencies, and Reachability
This chapter assumes you can already compute SCCs with Kosaraju's or Tarjan's algorithm and build the condensation DAG. It also assumes you know topological sorting and are comfortable reading Python. Chapter 15 covered 2-SAT. This chapter covers the other problems that SCC decomposition handles well: finding cycles, ordering dependencies, answering reachability queries, and reasoning about sources and sinks.
In each of these problems the hard part is that the graph has cycles. Most graph techniques assume a DAG. If you collapse each SCC to one node, every cycle disappears inside a node and a DAG is left. You then solve the problem on that DAG and map the answer back to the original vertices.
A Running Example: Module Imports
Suppose a codebase has seven modules. An edge A -> B means "A imports B", so B must be built before A.
| Module | Imports |
|---|---|
| app | ui, db |
| ui | core |
| core | ui, utils |
| utils | log |
| log | log (self-import) |
| db | cache |
| cache | db, utils |
The program below labels SCCs with an iterative Kosaraju (so deep graphs do not hit Python's recursion limit). It then uses the labels to detect cycles, produce a build order, answer reachability queries, and count sources and sinks. It is self-contained and runs as shown.
def scc_labels(n, adj):
"""Iterative Kosaraju. Components are numbered in topological
order of the condensation: every edge goes from a lower to a
higher (or equal) component number."""
visited = [False] * n
order = []
for s in range(n):
if visited[s]:
continue
visited[s] = True
stack = [(s, 0)]
while stack:
u, i = stack.pop()
if i < len(adj[u]):
stack.append((u, i + 1))
v = adj[u][i]
if not visited[v]:
visited[v] = True
stack.append((v, 0))
else:
order.append(u) # finish time
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
k = 0
for s in reversed(order):
if comp[s] != -1:
continue
comp[s] = k
stack = [s]
while stack:
u = stack.pop()
for v in radj[u]:
if comp[v] == -1:
comp[v] = k
stack.append(v)
k += 1
return comp, k
names = ["app", "ui", "core", "utils", "log", "db", "cache"]
idx = {name: i for i, name in enumerate(names)}
imports = {
"app": ["ui", "db"], "ui": ["core"], "core": ["ui", "utils"],
"utils": ["log"], "log": ["log"], "db": ["cache"],
"cache": ["db", "utils"],
}
n = len(names)
adj = [[idx[m] for m in imports[names[u]]] for u in range(n)]
comp, k = scc_labels(n, adj)
members = [[] for _ in range(k)]
for u in range(n):
members[comp[u]].append(u)
# Condensation DAG
dag = [set() for _ in range(k)]
for u in range(n):
for v in adj[u]:
if comp[u] != comp[v]:
dag[comp[u]].add(comp[v])
# 1. Cycle detection: an SCC is cyclic if it has 2+ vertices or a self-loop
for c in range(k):
m = members[c]
if len(m) > 1 or any(u in adj[u] for u in m):
print("cycle:", [names[u] for u in m])
# 2. Build order: dependencies first = reverse topological order
print("build order:", [[names[u] for u in members[c]] for c in reversed(range(k))])
# 3. Reachability: bitset per component, filled from sinks backward
reach = [0] * k
for c in reversed(range(k)):
bits = 1 << c
for d in dag[c]:
bits |= reach[d]
reach[c] = bits
def reaches(a, b):
return (reach[comp[idx[a]]] >> comp[idx[b]]) & 1 == 1
print(reaches("app", "log"), reaches("ui", "db"), reaches("cache", "db"))
# 4. Sources, sinks, and edges needed to make the graph strongly connected
indeg = [0] * k
for c in range(k):
for d in dag[c]:
indeg[d] += 1
sources = [c for c in range(k) if indeg[c] == 0]
sinks = [c for c in range(k) if not dag[c]]
print("edges to add:", 0 if k == 1 else max(len(sources), len(sinks)))Output:
cycle: ['db', 'cache']
cycle: ['ui', 'core']
cycle: ['log']
build order: [['log'], ['utils'], ['ui', 'core'], ['db', 'cache'], ['app']]
True False True
edges to add: 1Cycle Detection and Reporting
A directed graph has a cycle exactly when some SCC contains two or more vertices, or a single vertex with a self-loop. SCCs also tell you more than a plain DFS cycle check does. A DFS back-edge test answers yes or no and gives one cycle. The SCC decomposition gives every maximal group of vertices that are tangled together. That is the report users of a linter or build tool want: "these five modules form an import cycle", not just one arbitrary loop through them.
Some real uses:
- Deadlock detection. In a wait-for graph, an edge
T1 -> T2means transaction T1 waits for a lock that T2 holds. Any cyclic SCC is a set of deadlocked transactions. Aborting one member of each cyclic SCC breaks every cycle in it only if that member lies on all of the SCC's cycles, so detectors usually pick a victim and then recheck. - Spreadsheet formulas. A cell that depends on itself through other cells lies in a cyclic SCC. Spreadsheet programs report the whole SCC as the circular reference.
- Compiler loop analysis. In a control-flow graph, each nontrivial SCC contains at least one loop. Compilers use SCCs (and nested SCC decomposition) to find loop bodies and irreducible regions.
Dependency Ordering with Cycles Allowed
A plain topological sort fails as soon as there is a cycle. Condensing first gives you an order for any graph. Kosaraju numbers components in topological order, and Tarjan emits them in reverse topological order. When an edge means "depends on", reverse topological order is the order to build in, so Tarjan's output can be used without changes.
Within one SCC there is no valid order, because each member depends on the others through some path. Tools handle this in one of three ways:
- Reject the input and print the SCC (Go's import checker, most package managers).
- Process the SCC as one unit. Haskell's GHC compiles mutually recursive modules together, and type checkers infer types for each group of mutually recursive functions together.
- Iterate inside the SCC until a fixed point. Dataflow analyses and incremental build systems re-run the members of a cyclic SCC until nothing changes, then continue to the next component in topological order.
Reachability Queries
"Can u reach v?" costs O(V + E) per query with a fresh DFS. If many queries are asked, precompute. Two vertices in the same SCC reach exactly the same set of vertices, so you only need reachability between components. On the condensation you can fill reachability sets in reverse topological order, as the reach bitsets do above. Each component's set is its own bit plus the union of its successors' sets.
This costs O(k · m / w) time for k components, m condensation edges, and machine word size w, plus k² bits of memory. With Python's arbitrary-size integers it works well up to a few tens of thousands of components. Beyond that, k² bits becomes too large and you need labeling schemes or approximate methods. Condensing first can still shrink the problem a lot, because large real graphs such as web graphs and call graphs often have one giant SCC.
Sources, Sinks, and Making a Graph Strongly Connected
Sources (in-degree 0) and sinks (out-degree 0) of the condensation answer several structural questions:
| Question | Answer from the condensation |
|---|---|
| Is the graph strongly connected? | Exactly one component |
| Minimum start vertices so that every vertex is reachable | One vertex from each source component |
| Fewest edges to add to make the graph strongly connected | `max(#sources, #sinks)` if there are 2+ components, else 0 |
| States a Markov chain can never leave | Sink components (closed communicating classes) |
| Which vertex can reach all others? | One exists only if there is a single source component; then test any member |
The edge-count formula is a theorem by Eswaran and Tarjan (1976). In the example there is one source (app) and one sink (log), so a single edge log -> app makes the whole graph strongly connected.
In Markov chains, a sink SCC is a closed class, and a finite chain eventually ends up in one. Model checkers use the same idea. To check whether an automaton accepts some infinite run, they search for a reachable SCC that contains an accepting state and at least one cycle.
Common Mistakes
- Mixing up edge direction. If your edges mean "A is needed by B" instead of "A needs B", the build order flips. Choose one meaning, write it down, and check the result on a two-node example.
- Using a duplicate-edge list for in-degrees. Several original edges can map to the same condensation edge. Store successors in a set (as above), or source/sink counts and reachability will be wrong in some cases.
- Forgetting the single-component case in the edge-count formula. A strongly connected graph has one source and one sink, both the same component, but needs 0 edges.
Exercise
In the example, suppose you add the import "log -> cache". Which components merge, how many SCCs remain, and what is the new build order?
Show answer
Now log reaches cache, and cache already reaches log through utils (cache -> utils -> log). So db, cache, utils, and log form one SCC. ui and core still reach utils, but nothing in that new SCC leads back to them, so they stay a separate component. That leaves three SCCs: {app}, {ui, core}, and {db, cache, utils, log}. The build order is [db, cache, utils, log], then [ui, core], then [app]. The merged SCC must be built as one unit or reported as an import cycle.
Exercise
A directed graph's condensation has 4 source components and 2 sink components. What is the minimum number of edges you must add to make it strongly connected, and what is the minimum number of start vertices needed to reach every vertex?
Show answer
You need max(4, 2) = 4 added edges. You need 4 start vertices, one in each source component, because no vertex outside a source component can reach into it.
Exercise
Why is it enough to compute reachability between SCCs instead of between individual vertices?
Show answer
All vertices in one SCC can reach each other, so any vertex reachable from one member is reachable from every member. The vertex u reaches v exactly when comp[u] reaches comp[v] in the condensation, including the case comp[u] == comp[v].