Sub topic 16
More Applications: Cycles, Dependencies, and Reachability
This chapter assumes you can already compute a component labeling with Kosaraju's or Tarjan's algorithm and build the condensation DAG. Once you have those two results, several common graph questions take only a few lines of extra code.
Cycle Detection
A directed graph has a cycle exactly when some SCC contains more than one vertex, or when a single-vertex SCC has a self-loop. A self-loop is an edge from a vertex to itself. Plain DFS cycle detection, which looks for a back edge, only answers yes or no. An SCC decomposition also tells you which vertices take part in cycles, grouped by cycle cluster. That grouping is what you want when you report errors to a user.
A common mistake is to check only len(group) > 1. That check misses a vertex with an edge to itself.
Dependency Analysis
Build systems, package managers, and module loaders model "A depends on B" as an edge A → B. If the graph has a dependency cycle, a plain topological sort fails and gives you nothing useful. The condensation handles this case:
- Each SCC with more than one module is a circular dependency that must be reported or built as one unit.
- The condensation is always a DAG, so it can always be ordered.
- Kosaraju's numbering is a topological order of the condensation: components that depend on others come first. To build dependencies before the modules that use them, process components in decreasing component number. Tarjan's output order already does this, because it emits components in reverse topological order.
Reachability and Strong Connectivity
Mutual reachability inside an SCC means that u reaches v exactly when comp[u] reaches comp[v] in the condensation. The condensation is often much smaller than the original graph, so reachability queries are cheaper to answer there. For example, you can compute each component's reachable set with one pass over the DAG in reverse topological order.
The condensation also answers a classic question: how many edges must you add to make the whole graph strongly connected? Let s be the number of source components (no incoming edges) and t the number of sink components (no outgoing edges). The answer is max(s, t), except that it is 0 when there is only one component.
def kosaraju(n, adj):
visited, order = [False] * n, []
def dfs1(u):
visited[u] = True
for v in adj[u]:
if not visited[v]:
dfs1(v)
order.append(u)
for u in range(n):
if not visited[u]:
dfs1(u)
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
def dfs2(u, c):
comp[u] = c
for v in radj[u]:
if comp[v] == -1:
dfs2(v, c)
c = 0
for u in reversed(order):
if comp[u] == -1:
dfs2(u, c)
c += 1
return comp
def cyclic_groups(n, adj, comp):
groups = {}
for u in range(n):
groups.setdefault(comp[u], []).append(u)
return [g for g in groups.values()
if len(g) > 1 or g[0] in adj[g[0]]]
def edges_to_strongly_connect(n, adj, comp):
k = max(comp) + 1
if k == 1:
return 0
has_in, has_out = [False] * k, [False] * k
for u in range(n):
for v in adj[u]:
if comp[u] != comp[v]:
has_out[comp[u]] = True
has_in[comp[v]] = True
return max(has_in.count(False), has_out.count(False))
names = ["app", "auth", "db", "log", "utils"]
adj = [[1], [2], [1, 3], [4], [3]]
comp = kosaraju(5, adj)
print(comp) # [0, 1, 1, 2, 2]
for g in cyclic_groups(5, adj, comp):
print("cycle:", [names[u] for u in g]) # ['auth', 'db'], then ['log', 'utils']
print(edges_to_strongly_connect(5, adj, comp)) # 1The table lists more uses of the same pattern.
| Problem | How SCCs help |
|---|---|
| Deadlock detection | A cycle in a wait-for graph is a nontrivial SCC |
| Dead states in automata | States in sink components with no accepting state can never accept |
| Web or social graph analysis | The largest SCC is the graph's tightly linked core |
| 2-SAT | A variable and its negation in the same SCC means the formula is unsatisfiable |
Exercise
A graph has 6 vertices. Its condensation has 4 components, of which 2 are sources and 3 are sinks. What is the minimum number of edges you must add to make the graph strongly connected?
Show answer
max(2, 3) = 3. There is more than one component, so the formula applies directly.
Exercise
Every SCC in a graph has exactly one vertex. Is the graph a DAG?
Show answer
Only if no vertex has a self-loop. A self-loop is a cycle of length 1, and it does not make the SCC larger.