Sub topic 1
Directed Graphs and Mutual Reachability
Strongly connected components are built on one question: can you get from vertex u to vertex v and back again? This chapter sets out the vocabulary for that question. It covers directed graphs, paths, reachability, and the relation called mutual reachability, which splits a graph's vertices into groups. The next chapter names those groups. The rest of the tutorial shows how to find them quickly.
Prerequisites
This chapter assumes you already know:
- What a directed graph is and how to store one as an adjacency list.
- Depth-first search (DFS), at least in its recursive form.
- How stacks work, and basic recursion.
- Big-O notation, such as O(V + E).
- How to read simple Python: lists, sets, loops, and functions.
You don't need any graph theory beyond that. Terms such as path, reachable, and equivalence relation are defined below.
Directed Graphs and Their Representation
A directed graph G = (V, E) has a set of vertices V and a set of edges E. Each edge is an ordered pair (u, v), written u → v. The edge goes from u to v, and it does not let you travel from v to u. We write n = |V| and m = |E|.
Throughout the tutorial, vertices are numbered 0 to n - 1. The graph is stored as an adjacency list: adj[u] is the list of vertices v with an edge u → v. Here is the running example that later chapters also use:
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]That list encodes ten edges: 0→1, 1→2, 2→0, 2→3, 3→4, 4→5, 5→3, 6→5, 6→7, and 7→6.
Two details of the representation matter for everything that follows:
- Direction lives in the list. If
vis inadj[u], you can step fromutov. That says nothing about stepping fromvtou. - Self-loops and parallel edges are harmless. An edge u → u, or the same edge listed twice, never changes which vertices can reach which. The algorithms later in the tutorial handle both correctly.
Paths and Reachability
A path from u to v is a sequence of vertices u = x₀, x₁, …, xₖ = v where every consecutive pair xᵢ → xᵢ₊₁ is an edge. Its length is k, the number of edges. A path may repeat vertices. For reachability that never matters, because any path with a repeat can be shortened to one without repeats.
Vertex v is reachable from u, written u ⇝ v, when some path runs from u to v. The path of length 0 counts, so every vertex reaches itself: u ⇝ u always holds, even for an isolated vertex with no edges.
Reachability in a directed graph is not symmetric. In the example, 2 ⇝ 3 because of the edge 2→3. But no edge leaves the group {3, 4, 5} to go back toward 2, so 3 does not reach 2.
Computing the set of vertices reachable from a single source is one graph search. The version below uses an explicit stack, so deep graphs do not hit Python's recursion limit:
def reach_from(adj, s):
"""Return the set of vertices reachable from s (including s)."""
seen = {s}
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if v not in seen:
seen.add(v)
stack.append(v)
return seen
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(sorted(reach_from(adj, 0))) # [0, 1, 2, 3, 4, 5]
print(sorted(reach_from(adj, 3))) # [3, 4, 5]
print(sorted(reach_from(adj, 6))) # [3, 4, 5, 6, 7]
print(0 in reach_from(adj, 3)) # FalseEach vertex is pushed at most once and each edge is examined at most once, so one call costs O(n + m).
Mutual Reachability
Vertices u and v are mutually reachable, written u ↔ v, when u ⇝ v and v ⇝ u. You can travel from either one to the other.
Mutual reachability is an equivalence relation. That means it has three properties:
| Property | Statement | Why it holds |
|---|---|---|
| Reflexive | u ↔ u | The length-0 path gives u ⇝ u in both directions. |
| Symmetric | u ↔ v implies v ↔ u | The definition already treats both directions the same way. |
| Transitive | u ↔ v and v ↔ w imply u ↔ w | Join a path u ⇝ v to a path v ⇝ w to get u ⇝ w. Do the same backward to get w ⇝ u. |
Plain reachability (⇝) is reflexive and transitive, but it is not symmetric, so it is not an equivalence relation. Mutual reachability takes reachability and forces symmetry onto it.
An equivalence relation on a set always partitions that set. Every vertex lands in exactly one class, and two vertices share a class exactly when they are mutually reachable. Nothing is left over and no classes overlap. These classes are the strongly connected components that the next chapter defines formally.
Finding the Classes by Brute Force
The definition leads straight to an algorithm. Compute the reachable set from every vertex, then group u with every v where each one reaches the other:
def reach_from(adj, s):
seen = {s}
stack = [s]
while stack:
u = stack.pop()
for v in adj[u]:
if v not in seen:
seen.add(v)
stack.append(v)
return seen
def mutual_classes(adj):
n = len(adj)
reach = [reach_from(adj, u) for u in range(n)]
label = [-1] * n
classes = []
for u in range(n):
if label[u] != -1:
continue
cls = sorted(v for v in reach[u] if u in reach[v])
for v in cls:
label[v] = len(classes)
classes.append(cls)
return classes
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(mutual_classes(adj)) # [[0, 1, 2], [3, 4, 5], [6, 7]]The output gives three classes. Vertices 0, 1, and 2 lie on a common cycle. So do 3, 4, and 5, and so do 6 and 7. The edges 2→3 and 6→5 connect different classes in one direction only, so they never merge two classes.
Why Brute Force Is Not Enough
The function makes n searches, each costing O(n + m), for a total of O(n(n + m)). It also stores n reachable sets, which can use O(n²) memory. Take a dependency graph with n = 10⁵ and m = 10⁶. The time bound comes to about 10¹¹ steps, and the memory can reach 10¹⁰ set entries. That is far too much. Kosaraju's and Tarjan's algorithms find the same partition in O(n + m) time, which here is about 1.1 × 10⁶ steps. Keep mutual_classes anyway. It is short and obviously correct, so it makes a good test oracle when you check your faster implementations on small random graphs.
Common Errors
These mistakes come up often when people start reasoning about directed reachability:
- Ignoring direction. If you treat edges as undirected, the example graph becomes one connected piece. Connectivity with direction ignored is called weak connectivity, and it is a much coarser partition. The example is weakly connected, yet it has three mutual-reachability classes.
- Dropping singleton classes. A vertex with no cycle through it still forms a class of its own, because u ↔ u always holds. An algorithm that reports only groups of two or more vertices is wrong.
- Requiring a single cycle through every pair. Two vertices in the same class need a route each way, and those routes may share vertices or wander through other parts of the class. They do not have to lie together on one simple cycle.
- Assuming one-way edges merge classes. One edge from class A to class B, or many edges in the same direction, never joins A and B. Only paths in both directions do.
- Reversing the adjacency convention. Some sources store incoming neighbors in
adj[u]. If you mix the two conventions you get the transpose of the graph you meant. For mutual reachability the classes come out the same, but the direction-sensitive steps in Kosaraju's algorithm will break.
Exercises
Exercise
A graph on vertices 0–5 has edges 0→1, 1→0, 1→2, 2→3, 3→4, 4→2, 5→4. List its mutual-reachability classes and say whether the graph is weakly connected.
Show answer
The classes are {0, 1}, {2, 3, 4}, and {5}. Vertices 0 and 1 reach each other. Vertices 2, 3, and 4 form the cycle 2→3→4→2. Vertex 5 reaches 4 but nothing returns to 5, so 5 forms a class by itself. If you ignore direction, every vertex connects to every other, so the graph is weakly connected and forms a single undirected piece.
Exercise
Prove that if u ↔ v and v ↔ w, then u ↔ w. Then explain why this fact means a vertex can never belong to two different classes.
Show answer
From u ⇝ v and v ⇝ w, joining the two paths gives a path u ⇝ w. From w ⇝ v and v ⇝ u, joining gives w ⇝ u. So u ↔ w. Now suppose vertex v belonged to two classes, one containing u and one containing w. Then u ↔ v and v ↔ w, so u ↔ w, and the two classes would be the same class. Therefore the classes are disjoint.
Exercise
A graph has n = 50,000 vertices and m = 200,000 edges. Roughly how many basic steps does the brute-force mutual_classes function take, and how does that compare with an O(n + m) algorithm?
Show answer
Brute force runs n searches of O(n + m) each: 50,000 × 250,000 = 1.25 × 10¹⁰ steps. A linear-time algorithm takes about n + m = 2.5 × 10⁵ steps, which is 50,000 times fewer. The brute-force reachable sets can also use up to n² = 2.5 × 10⁹ entries of memory.