Sub topic 2
What a Connected Component Is
This chapter defines connected components exactly enough that you can check any algorithm's output against the definition. It assumes you can read Python with lists, loops, and functions. It also assumes you know basic graph vocabulary (vertex, edge, directed versus undirected) and Big-O notation. It also assumes the adjacency-list representation from the previous chapter. Everything here concerns undirected graphs. Directed graphs need two different notions of connectivity, and later chapters cover them.
Paths and Reachability
A path from vertex u to vertex v is a sequence of vertices u = x0, x1, ..., xk = v where each consecutive pair (xi, xi+1) is an edge. The length of the path is k, the number of edges used. A path of length 0 is just the single vertex u. It always exists, even if u has no edges.
Vertex v is reachable from u if some path from u to v exists. In an undirected graph, every edge works in both directions, so reachability does too. If you can walk from u to v, you can walk the same edges backward from v to u.
Reachability Is an Equivalence Relation
Write u ~ v when v is reachable from u. This relation has three properties:
| Property | Statement | Why it holds |
|---|---|---|
| Reflexive | `u ~ u` for every `u` | The length-0 path |
| Symmetric | `u ~ v` implies `v ~ u` | Reverse the path; undirected edges work both ways |
| Transitive | `u ~ v` and `v ~ w` imply `u ~ w` | Join the two paths end to end |
A relation with all three properties is an equivalence relation. Every equivalence relation splits its set into disjoint equivalence classes: groups where every member is related to every other member and to nothing outside the group.
The connected components are the equivalence classes of reachability. That one sentence gives you three guarantees:
- Every vertex belongs to exactly one component.
- Components never overlap.
- Two vertices are in the same component exactly when a path joins them.
The Formal Definition
A connected component of an undirected graph G is a maximal connected subgraph of G. "Connected" means every pair of its vertices is joined by a path. "Maximal" means you cannot add another vertex of G and keep it connected.
Maximality is the part people forget. In the graph below, the set {0, 1} is connected, but it is not a component, because vertex 2 can be added and the set stays connected. The component is {0, 1, 2}.
A component includes its vertex set and every edge of G between those vertices. In practice, algorithms report only the vertex sets, because the edges follow from them.
Edge Cases the Definition Settles
The definition gives a clear answer for each awkward input, and code has to match it.
- Isolated vertices. A vertex with no edges is a component of size 1, because of the length-0 path. Vertex 5 above counts. Leaving it out undercounts the components.
- Vertices missing from the edge list. An edge list alone cannot show an isolated vertex. That is why the code in this tutorial takes
nas a separate argument. If you computenasmax(endpoint) + 1, you silently drop isolated vertices with high ids. - Self-loops. An edge
(u, u)connectsuto itself, which reflexivity already gives you. It never changes the components. - Parallel edges. Two copies of
(u, v)connect the same pair twice. Components depend only on whether a path exists, not on how many paths there are. - The empty graph. With
n = 0there are zero components. Withn > 0and no edges, there arencomponents. - A connected graph. "G is connected" means G has exactly one component.
Counting Facts Worth Knowing
Let V be the number of vertices, E the number of edges, and c the number of components.
Start with V vertices and no edges, so c = V. Add the edges one at a time. Each edge either joins two different components, which lowers c by exactly 1, or lands inside one component, which leaves c unchanged. This gives:
c ≥ V − Efor every graph. The count can drop by at most one per edge.c = V − Eexactly when no edge closes a cycle, that is, when the graph is a forest.- A connected graph needs at least
V − 1edges. A connected graph with exactlyV − 1edges is a tree.
The same argument, applied one edge at a time, is the basis of union-find and incremental connectivity later in the tutorial. The bound also makes a quick sanity check. If your code reports fewer than V − E components, it has a bug.
Two Ways to Report the Answer
Algorithms usually return the components in one of two forms.
| Form | Example for the graph above | Good for |
|---|---|---|
| Label array | `[0, 0, 0, 1, 1, 2]` | Answering "are `u` and `v` connected?" in O(1) by comparing `label[u] == label[v]` |
| List of vertex sets | `[[0, 1, 2], [3, 4], [5]]` | Iterating over each component, finding sizes, extracting subgraphs |
Both forms carry the same information. The actual label numbers are arbitrary. [7, 7, 7, 2, 2, 9] describes the same partition. When you compare two algorithms' outputs, compare the partitions they describe, not the raw label values.
An Algorithm Taken Straight from the Definition
You can compute components using nothing but the facts above. Give every vertex its own id as a label. Then, for every edge, set both endpoints to the smaller of their two labels. Keep sweeping over the edges until nothing changes. Because labels only decrease and are bounded below, the process stops. When it stops, every edge has equal labels at both ends, so every path has a single label along its whole length. Each component ends up labeled with its smallest vertex id.
def components_by_relaxation(n, edges):
label = list(range(n))
passes = 0
changed = True
while changed:
changed = False
passes += 1
for u, v in edges:
m = min(label[u], label[v])
if label[u] != m or label[v] != m:
label[u] = label[v] = m
changed = True
return label, passes
def same_partition(a, b):
"""True if two label arrays describe the same grouping of vertices."""
if len(a) != len(b):
return False
forward, backward = {}, {}
for x, y in zip(a, b):
if forward.setdefault(x, y) != y or backward.setdefault(y, x) != x:
return False
return True
labels, passes = components_by_relaxation(6, [(0, 1), (1, 2), (3, 4)])
print(labels, passes) # [0, 0, 0, 3, 3, 5] 2
print(same_partition(labels, [0, 0, 0, 1, 1, 2])) # True
print(same_partition(labels, [0, 0, 1, 1, 1, 2])) # False
# Edge order matters for speed: a path listed backward needs many passes.
n = 6
path_backward = [(i, i + 1) for i in reversed(range(n - 1))]
print(components_by_relaxation(n, path_backward)) # ([0, 0, 0, 0, 0, 0], 6)The second function, same_partition, is useful for testing. It checks that the mapping between the two label arrays is one-to-one, so the arrays group the vertices the same way even when the label numbers differ.
The last example shows why this method is only a teaching tool. A label can move only one edge per pass when the edges are listed in an unhelpful order. That means up to about V passes of E work each, which is O(V·E) in the worst case. The traversal methods in the next chapters reach every vertex and edge a constant number of times and run in O(V + E).
Common Errors
- Treating "connected subset" as "component." A component must be maximal. Reporting
{0, 1}instead of{0, 1, 2}is wrong. - Forgetting isolated vertices, usually because
nwas inferred from the edges. - Adding each undirected edge in only one direction when building the adjacency list. A traversal from vertex 1 then fails to reach vertex 0, and one component gets reported as several.
- Comparing label values instead of partitions when testing two implementations against each other.
- Applying the undirected definition to a directed graph. With direction,
vreachable fromuno longer impliesureachable fromv. Symmetry fails, so reachability alone is not an equivalence relation. The directed-graph chapters restore it in two different ways: by ignoring direction (weak components) or by requiring reachability both ways (strong components).
Exercises
Exercise
A graph has 10 vertices and 4 edges. What are the smallest and largest possible numbers of connected components?
Show answer
The smallest is 10 − 4 = 6, reached when no edge closes a cycle (the graph is a forest). The largest is 8: put all 4 edges inside a triangle with one doubled edge (or a self-loop), so only 2 of the 10 vertices merge with others... more precisely, the 4 edges must touch as few vertices as possible. A triangle on 3 vertices plus one parallel edge or self-loop uses 3 vertices in one component, leaving 7 isolated vertices, for 8 components. With a simple graph, 4 edges need at least 4 vertices (4 vertices allow up to 6 edges), giving 1 + 6 = 7 components.
Exercise
For edges [(0, 0), (1, 2), (2, 1), (4, 5)] and n = 7, list the connected components.
Show answer
{0}, {1, 2}, {3}, {4, 5}, {6}. The self-loop on 0 and the duplicated edge between 1 and 2 change nothing. Vertices 3 and 6 are isolated and still count as components.
Exercise
Do the label arrays [5, 5, 2, 2, 9] and [0, 0, 1, 1, 1] describe the same components? Explain using same_partition's logic.
Show answer
No. The first array puts vertex 4 in its own group, label 9. The second puts vertex 4 with vertices 2 and 3, label 1. In same_partition, label 1 is first matched to label 2 (at vertex 2). At vertex 4 the backward map would need label 1 to match label 9 as well, so the function returns False.
Exercise
Why does the undirected definition of a component fail on a directed graph with the single edge 0 → 1?
Show answer
Vertex 1 is reachable from 0, but 0 is not reachable from 1, so reachability is not symmetric. Without symmetry the relation is not an equivalence relation, so it does not split the vertices into well-defined classes. You must either ignore direction (giving weak components) or require reachability both ways (giving strong components).