Sub topic 7
Connectivity: components and reachability
This chapter assumes you know the dictionary-of-dictionaries adjacency list from the earlier chapters, including the add_edge helper. It also assumes you know sets and stacks, and the idea of a path as a sequence of edges.
Reachability
Vertex v is reachable from vertex u if a path leads from u to v. Every vertex is reachable from itself by a path of length zero.
In an undirected graph, reachability is symmetric. If you can get from u to v, you can get back. In a directed graph it is not. A path A → B → C makes C reachable from A, but A is not reachable from C.
The code below finds every vertex reachable from a start vertex. It keeps a stack of vertices to visit and a set of vertices already seen.
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}
stack = [start]
while stack:
u = stack.pop()
for v in graph[u]:
if v not in seen:
seen.add(v)
stack.append(v)
return seen
d = {}
add_edge(d, "A", "B", directed=True)
add_edge(d, "B", "C", directed=True)
print(sorted(reachable(d, "A"))) # ['A', 'B', 'C']
print(sorted(reachable(d, "C"))) # ['C']Each vertex enters the stack at most once, so the cost is O(V + E).
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 group of vertices that can all reach each other. "Maximal" means you cannot add another vertex to the group and keep that property.
A vertex with no edges forms a component of its own.
def components(graph):
remaining = set(graph)
result = []
while remaining:
start = next(iter(remaining))
comp = reachable(graph, start)
result.append(comp)
remaining -= comp
return result
g = {}
add_edge(g, "A", "B")
add_edge(g, "B", "C")
add_edge(g, "D", "E")
g.setdefault("F", {}) # an isolated vertex
print(sorted(sorted(c) for c in components(g)))
# [['A', 'B', 'C'], ['D', 'E'], ['F']]The loop picks any unvisited vertex, collects everything reachable from it, and removes that group from remaining. Every vertex is visited once overall, so the total cost is still O(V + E).
Connectivity in directed graphs
Direction splits connectivity into two kinds.
- A directed graph is strongly connected if every vertex is reachable from every other vertex, following edge directions.
- A directed graph is weakly connected if it becomes connected once you ignore edge directions.
The graph A → B → C is weakly connected but not strongly connected. Adding the edge C → A closes a cycle and makes it strongly connected.
A strongly connected component is a maximal set of vertices that can all reach each other. Every graph has a unique split into such components. Efficient algorithms for finding them exist, but they are beyond this chapter. A simple check for the whole graph is to run reachable from every vertex:
def is_strongly_connected(graph):
everything = set(graph)
return all(reachable(graph, u) == everything for u in graph)
print(is_strongly_connected(d)) # False
add_edge(d, "C", "A", directed=True)
print(is_strongly_connected(d)) # TrueThis costs O(V × (V + E)), which is fine for small graphs.
Common errors
- Forgetting isolated vertices. If you build the graph only from an edge list, a vertex with no edges never appears as a key and is silently missing from the components.
- Missing the seen set. Without it, a graph containing a cycle makes the search loop forever.
- Mixing up the two directed meanings. Weak connectivity ignores direction, and strong connectivity respects it. A graph can be one without the other.
Exercise
A directed graph has edges A → B, B → C, and C → B. Is it strongly connected? Which vertices are reachable from C?
Show answer
No. A is not reachable from B or C, because no edge points into A. From C you can reach C and B, so the set is {B, C}. The graph is weakly connected, since ignoring directions links all three vertices.