Sub topic 10
Connectivity When Edges Have Direction
This chapter assumes you already know how to build an adjacency list from an edge list and how to label undirected components with BFS or iterative DFS. It also assumes you are comfortable with Big-O notation and the difference between directed and undirected edges. Here we work out what "connected" means once edges point one way, why the undirected labeling loop gives wrong answers on directed graphs, and how the correct definitions lead to the algorithms in the next three chapters.
Reachability Is No Longer Symmetric
In an undirected graph, an edge {u, v} lets you move both ways. If u can reach v, then v can reach u by walking the same path backward. That symmetry is why "is connected to" splits the vertices cleanly into components.
In a directed graph, an edge u → v lets you move from u to v only. Vertex v reaches vertex u only if some separate directed path leads back. So reachability becomes a one-way relation:
- Reachable:
vis reachable fromuif there is a directed pathu → … → v. Every vertex is reachable from itself by the empty path. - Mutually reachable:
uandvare mutually reachable if each is reachable from the other.
Take this four-vertex graph, which we use for the rest of the chapter:
Vertex 0 reaches every vertex, including 3. Vertex 3 reaches only itself. So 0 and 3 are "connected" in one sense and not in another, and the undirected notion of a component cannot express that.
Two Definitions of a Directed Component
Directed graphs have two standard kinds of component, and they answer different questions.
A strongly connected component (SCC) is a maximal set of vertices in which every pair is mutually reachable. Mutual reachability is reflexive, symmetric, and transitive, so it is an equivalence relation. That means it partitions the vertices, and every vertex belongs to exactly one SCC. In the example, the SCCs are {0, 1, 2} and {3}.
A weakly connected component (WCC) is a component of the graph you get by ignoring edge directions. In the example, there is one WCC, {0, 1, 2, 3}, because the edge 2 → 3 links 3 to the rest once direction is dropped.
| Notion | Graph type | Two vertices share a component when | Example result |
|---|---|---|---|
| Connected component | Undirected | A path joins them | n/a |
| Weakly connected component | Directed | A path joins them once directions are ignored | `{0,1,2,3}` |
| Strongly connected component | Directed | Each reaches the other along directed paths | `{0,1,2}`, `{3}` |
Every SCC sits inside a single WCC, because a directed path in each direction is still a path once direction is ignored. The reverse does not hold. A graph is strongly connected if it has exactly one SCC, and weakly connected if it has exactly one WCC.
Which one you want depends on the question. "Which accounts are in the same transaction network at all?" calls for weak components. "Which web pages can all reach one another by following links?" or "Which modules form a circular import?" calls for strong components.
The Common Error: Running Undirected Labeling on a Directed Adjacency List
The most frequent bug is reusing the undirected BFS labeling loop on a directed adjacency list that stores only u → v. It runs without errors and returns plausible labels, but the labels depend on which start vertex the outer loop tries first. The function below takes an explicit order so you can see the effect:
from collections import deque
def label_directed_naive(n, edges, order):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v) # one direction only
label = [-1] * n
count = 0
for start in order:
if label[start] != -1:
continue
label[start] = count
queue = deque([start])
while queue:
u = queue.popleft()
for v in adj[u]:
if label[v] == -1:
label[v] = count
queue.append(v)
count += 1
return count, label
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
print(label_directed_naive(4, edges, [0, 1, 2, 3])) # (1, [0, 0, 0, 0])
print(label_directed_naive(4, edges, [3, 2, 1, 0])) # (2, [1, 1, 1, 0])Neither answer is a weak or strong decomposition, even though the second happens to look like one. Starting at 0, BFS reaches everything and lumps 3 in with the cycle, which is wrong for SCCs. Starting at 3, BFS finds only {3}, and then 2 reaches 3 but 3 is already labeled, so the split looks right only because of the order. Change the graph slightly and the reverse order breaks too. A single forward traversal computes the set reachable from the start, nothing more. Because reachability is one-way, that set is not an equivalence class.
Testing Strong Connectivity with Two Traversals
Here is a useful fact: a graph is strongly connected if and only if, for some fixed vertex s, every vertex is reachable from s and s is reachable from every vertex.
The first half is one forward traversal from s. For the second half, build the reverse graph (also called the transpose), where every edge u → v becomes v → u. A path from x to s in the original graph is a path from s to x in the reverse graph. So "everyone reaches s" becomes "s reaches everyone in the reverse graph," which is one more traversal.
Why is this enough? If every vertex reaches s and s reaches every vertex, then any u and v are mutually reachable through s: u → s → v and v → s → u.
def reachable(adj, s):
seen = [False] * len(adj)
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 build(n, edges):
adj = [[] for _ in range(n)]
radj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
radj[v].append(u)
return adj, radj
def is_strongly_connected(n, edges):
if n == 0:
return True
adj, radj = build(n, edges)
return all(reachable(adj, 0)) and all(reachable(radj, 0))
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
print(is_strongly_connected(4, edges)) # False
print(is_strongly_connected(4, edges + [(3, 0)])) # TrueThis runs in O(V + E) time and O(V + E) space: two traversals plus the reversed copy of the edges. The reverse graph shows up again in Kosaraju's algorithm.
A Correct but Slow SCC Algorithm
The same idea generalizes. The SCC containing s is exactly the set of vertices that are both reachable from s (forward traversal) and able to reach s (traversal on the reverse graph). Intersect the two sets, label them, and move on to the next unlabeled vertex:
def scc_brute_force(n, edges):
adj, radj = build(n, edges)
comp = [-1] * n
count = 0
for s in range(n):
if comp[s] != -1:
continue
forward = reachable(adj, s)
backward = reachable(radj, s)
for v in range(n):
if forward[v] and backward[v]:
comp[v] = count
count += 1
return count, comp
print(scc_brute_force(4, [(0, 1), (1, 2), (2, 0), (2, 3)]))
# (2, [0, 0, 0, 1])This is correct for any start order. If a vertex v in the intersection already had a label, v and s would be mutually reachable, so s would have received the same label earlier and been skipped.
The cost is the problem. The loop does two full traversals per SCC, and each can touch the whole graph. A directed acyclic graph (DAG) has V singleton SCCs, so the worst case is O(V · (V + E)). On a million-vertex dependency graph that is far too slow. Kosaraju's and Tarjan's algorithms, covered in later chapters, get the same result in O(V + E) by ordering the traversals cleverly so that no work repeats.
The Condensation Is Always a DAG
If you collapse each SCC into a single node and keep an edge between two SCCs whenever some original edge crosses between them, you get the condensation of the graph.
The condensation never contains a cycle. Suppose SCCs X and Y had edges X → Y and Y → X. Then every vertex in X could reach every vertex in Y and back, so X and Y would be one SCC, which contradicts their being separate maximal sets. The same argument rules out longer cycles.
This property has practical uses:
- Build systems and package managers condense the dependency graph. Each nontrivial SCC is a circular dependency to report. The condensation can then be topologically sorted.
- 2-SAT solvers check whether a variable and its negation land in the same SCC of the implication graph.
- Static analysis treats mutually recursive functions (one SCC of the call graph) as a single unit.
Edge Cases Worth Checking
| Situation | Effect on SCCs | Effect on WCCs |
|---|---|---|
| Isolated vertex | Its own SCC | Its own WCC |
| Self-loop `v → v` | No change; `v` was already its own SCC or more | No change |
| Duplicate edges | No change; traversal may scan them twice | No change |
| DAG | Every vertex is a singleton SCC | Same as undirected components of the underlying graph |
| Single cycle through all vertices | One SCC | One WCC |
| Adding edge `u → v` | Can merge several SCCs at once if `v` already reaches `u` | Merges at most two WCCs |
The last row matters for the incremental methods from the union-find chapters. Weak connectivity under edge insertion works the same as undirected connectivity, so union-find handles it directly. Strong connectivity does not: one new edge can close a cycle that passes through many SCCs and merge them all, and union-find has no way to detect that. Deleting an edge can split one SCC into many. Incremental SCC maintenance is a research-level problem, and most practical code just recomputes.
Exercise
A directed graph has edges 0→1, 1→2, 2→3, 3→1, 4→3. List its strongly connected components and its weakly connected components.
Show answer
SCCs: {0}, {1, 2, 3}, {4}. Vertices 1, 2, 3 form the cycle 1→2→3→1; 0 can reach the cycle but nothing returns to 0, and 4 likewise only points in. WCCs: one component {0, 1, 2, 3, 4}, since ignoring direction connects every vertex.
Exercise
Why does isstronglyconnected need a traversal on the reverse graph, rather than just checking that a forward traversal from vertex 0 reaches every vertex?
Show answer
A forward traversal only proves that 0 reaches everyone. In the graph 0→1, 0→2, vertex 0 reaches all vertices but neither 1 nor 2 can reach 0, so the graph is not strongly connected. The reverse-graph traversal checks the other direction, that every vertex reaches 0, which together with the forward check gives mutual reachability between every pair through 0.
Exercise
In the worst case, how many traversals does sccbruteforce perform on a DAG with V vertices, and what is its total time complexity?
Show answer
A DAG has V singleton SCCs, so the outer loop runs a forward and a backward traversal for every vertex: 2V traversals. Each costs O(V + E), giving O(V · (V + E)) total time.