Connected Components
–
Pseudocode
1comp ← 0; label[v] ← none for every vertex2for each vertex s:3 if label[s] is none:4 comp ← comp + 15 flood fill from s (DFS): label[v] ← comp for every vertex reached6// vertices with the same label are connected to each other
Components
0
Labelled
0
vertex just reached#2component number
What are Connected Components?
A connected component is a group of vertices where you can get from any vertex to any other along edges, and nothing outside the group is reachable. A graph made of three separate islands has three components.
To find them, walk through the vertices in order. Whenever a vertex has no label yet, it must belong to a new component: flood fill from it with DFS (or BFS) and give every vertex it reaches that component's number.
Every unlabelled vertex starts a new component; flood fill labels the rest of it.
Using the Visualizer
- • Each colour is one component; #2 next to a vertex is its component number.
- • Open Edit graph and add one edge between two colours: they become one component.
- • The label[] row on the right is exactly the array the code fills in.
How It Works
1. Scan the vertices
In order 0, 1, 2, … looking for one with no label.
2. New component
An unlabelled vertex starts component number count + 1.
3. Flood fill
DFS from it: every vertex reached gets the same label.
4. Done
After the scan, the number of flood fills is the number of components.
Implementation
Properties & Complexity
Time Complexity
- • Adjacency list: O(V + E)
- • Adjacency matrix: O(V²)
Space & Properties
- • Space: O(V) for labels and the stack
- • Directed graphs: need strongly connected components instead
Where It Is Used
- • Image processing: separate blobs in a picture (flood fill)
- • Networks: which computers can talk to each other
- • Social graphs: groups of people linked by friendships
- • Checking connectivity before running MST or shortest paths
Limitations
- • Undirected only: one-way edges need SCC algorithms
- • Static: recompute after edges change, or use Union-Find for added edges