VLVisual Learner

Connected Components

Time: O(V + E)Space: O(V)Undirected graphs
–
Pseudocode
1comp ← 0; label[v] ← none for every vertex
2for each vertex s:
3 if label[s] is none:
4 comp ← comp + 1
5 flood fill from s (DFS): label[v] ← comp for every vertex reached
6// 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

// Label the connected components of an undirected graph.
// graph[u][v] = 1 when u and v are joined. Returns label[v] = component number.
function connectedComponents(graph) {
  const n = graph.length;
  const label = Array(n).fill(-1);
  let count = 0;

  for (let s = 0; s < n; s++) {
    if (label[s] !== -1) continue;       // already part of a component
    const stack = [s];                   // flood fill (DFS) from s
    label[s] = count;
    while (stack.length) {
      const u = stack.pop();
      for (let v = 0; v < n; v++) {
        if (graph[u][v] && label[v] === -1) {
          label[v] = count;
          stack.push(v);
        }
      }
    }
    count++;
  }
  return { count, label };
}

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