Sub topic 7
Connectivity: components and reachability
This chapter assumes you know what vertices, edges, paths, and cycles are, and that you can read the dictionary-of-dictionaries adjacency list from the earlier chapters. You should also be comfortable with a queue and with Python sets. Here you will use paths to answer two questions. Can I get from one vertex to another? Does the graph fall into separate pieces?
Reachability
Vertex v is reachable from vertex u if a path leads from u to v. A path of zero edges counts, so every vertex reaches itself.
In an undirected graph, reachability is symmetric. If you can walk from u to v, you can walk the same edges backward. In a directed graph it is not symmetric. A one-way street from A to B says nothing about getting from B back to A.
Reachability is the basic question behind many practical problems:
- Can this packet get from one router to another?
- Does this module depend, directly or indirectly, on that one?
- Are these two users in the same friend network?
You answer it with a traversal. Breadth-first search from u visits exactly the vertices reachable from u, and nothing else. The set of vertices it marks as seen is the answer.
from collections import deque
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
def reachable(graph, start):
seen = {start}
queue = deque([start])
while queue:
u = queue.popleft()
for v in graph[u]:
if v not in seen:
seen.add(v)
queue.append(v)
return seen
g = {}
add_edge(g, "A", "B")
add_edge(g, "B", "C")
add_edge(g, "D", "E")
g.setdefault("F", {}) # an isolated vertex: no edges at all
print(sorted(reachable(g, "A"))) # ['A', 'B', 'C']
print("E" in reachable(g, "A")) # FalseThis is the same BFS as before, except that it returns the seen set instead of the visit order. The cost is O(V + E) in the worst case, because each vertex is queued once and each adjacency entry is examined once. Set lookups and insertions are O(1) on average.
Connected components in undirected graphs
An undirected graph is connected if every vertex is reachable from every other vertex. If it is not, it splits into connected components. A component is a maximal set of vertices that are all mutually reachable. "Maximal" means you cannot add another vertex without breaking that property.
The example graph above has three components: {A, B, C}, {D, E}, and {F}. Note that an isolated vertex is a component by itself.
Components have three properties you can rely on:
- Every vertex belongs to exactly one component.
- No edge crosses between two components. If one did, the two components would merge.
- Reachability is an equivalence relation on an undirected graph. It is reflexive, symmetric, and transitive, and the components are its equivalence classes.
To find all components, run a traversal from any vertex, collect what it reaches, and then repeat from a vertex you have not yet assigned.
def components(graph):
assigned = set()
result = []
for start in graph:
if start not in assigned:
comp = reachable(graph, start)
result.append(comp)
assigned |= comp
return result
def is_connected(graph):
if not graph:
return True # convention: the empty graph counts as connected
start = next(iter(graph))
return len(reachable(graph, start)) == len(graph)
print([sorted(c) for c in components(g)]) # [['A', 'B', 'C'], ['D', 'E'], ['F']]
print(is_connected(g)) # FalseThe total cost is still O(V + E). The outer loop visits each vertex once. Each inner traversal only touches vertices that no earlier traversal has assigned, so no edge is examined more than once per endpoint.
Reachability in directed graphs
Direction splits connectivity into two notions.
| Term | Definition | Test |
|---|---|---|
| Weakly connected | Ignoring edge directions, the graph is connected | One traversal on the undirected version |
| Strongly connected | Every vertex is reachable from every other, following directions | Every vertex reaches every other along directed paths |
Strong connectivity implies weak connectivity, but not the other way around. A directed graph can be weakly connected and still have vertices you can never get back from.
Consider this graph. Three vertices form a cycle, and one more hangs off the end.
From A you can reach every vertex. From D you can reach only D. The cycle A → B → C → A means those three vertices reach one another, but D is a dead end.
A strongly connected component (SCC) is a maximal set of vertices that are all mutually reachable by directed paths. This graph has two: {A, B, C} and {D}.
Testing strong connectivity
A vertex v is in the same SCC as s exactly when v is reachable from s and s is reachable from v. You can compute the first set with a normal traversal. For the second set, traverse the reverse graph, which has the same vertices but every edge flipped. Then v is reachable from s in the reverse graph exactly when s is reachable from v in the original.
def reverse(graph):
rev = {u: {} for u in graph}
for u in graph:
for v, w in graph[u].items():
rev[v][u] = w
return rev
def undirected_view(graph):
view = {u: {} for u in graph}
for u in graph:
for v, w in graph[u].items():
view[u][v] = w
view[v][u] = w
return view
def is_strongly_connected(graph):
if not graph:
return True
start = next(iter(graph))
return (len(reachable(graph, start)) == len(graph)
and len(reachable(reverse(graph), start)) == len(graph))
def strongly_connected_components(graph):
rev = reverse(graph)
assigned = set()
result = []
for v in graph:
if v not in assigned:
comp = reachable(graph, v) & reachable(rev, v)
result.append(comp)
assigned |= comp
return result
d = {}
add_edge(d, "A", "B", directed=True)
add_edge(d, "B", "C", directed=True)
add_edge(d, "C", "A", directed=True)
add_edge(d, "C", "D", directed=True)
print(is_strongly_connected(d)) # False
print(is_connected(undirected_view(d))) # True
print([sorted(c) for c in strongly_connected_components(d)]) # [['A', 'B', 'C'], ['D']]is_strongly_connected needs only two traversals from one start vertex. If every vertex is reachable from start, and start is reachable from every vertex, then any two vertices can reach each other by going through start.
The strongly_connected_components function above is easy to verify, but it can run a pair of traversals for every vertex that starts a new component. In the worst case that is O(V · (V + E)). Kosaraju's and Tarjan's algorithms find all SCCs in O(V + E) with depth-first search. This tutorial does not cover them. Use the simple version when graphs are small or clarity matters.
Edge cases and common errors
- Missing vertex keys.
reachabledoesgraph[u]for every discovered vertex. If a vertex appears only as an edge target and has no key of its own, you get aKeyError. Theadd_edgehelper avoids this by callinggraph.setdefault(v, {}). Hand-built dictionaries need the same care, and vertices with no outgoing edges need an empty inner dictionary. - Forgetting that direction matters.
reachable(d, "D")returns{"D"}, whilereachable(d, "A")returns all four vertices. Calling the first result "the component of D" is wrong in a directed graph. Say "the set reachable from D." - Marking vertices too late. Add a vertex to
seenwhen you enqueue it, not when you dequeue it. Otherwise one vertex can be queued many times, and the O(V + E) bound no longer holds. - Looping from one start only. A single traversal finds one component. To list all components, loop over every vertex and skip the ones already assigned, as
componentsdoes. - Counting components with edges only. A vertex with no edges is still a component. Building the vertex set from the edge list alone will miss isolated vertices.
Why this matters for later chapters
Many algorithms need connectivity first. Dijkstra's algorithm only assigns distances to vertices reachable from the source, and the others never appear in its result. A minimum spanning tree exists only for a connected graph. For a graph with several components, you can compute one spanning tree per component. Directed acyclic graphs, covered later, are the directed graphs in which every strongly connected component is a single vertex.
Exercise
A directed graph has the edges 1→2, 2→3, 3→1, and 4→3. How many weakly connected components and how many strongly connected components does it have? Name the vertices in each.
Show answer
It has one weakly connected component, {1, 2, 3, 4}, because ignoring directions every vertex is linked to the others. It has two strongly connected components: {1, 2, 3}, which form the cycle 1→2→3→1, and {4}. Vertex 4 can reach the cycle, but nothing in the cycle can reach 4.
Exercise
Using only the functions in this chapter, write a function same_component(graph, u, v) for an undirected graph. What is its time complexity, and how would you make repeated queries cheaper?
Show answer
def same_component(graph, u, v): return v in reachable(graph, u). It runs in O(V + E) per query. For many queries, run components once, store a dictionary that maps each vertex to its component number, and then answer each query with two dictionary lookups in O(1).