Skip to lesson

Connected components

Connected components partition an undirected graph into maximal sets of mutually reachable vertices.

Counting connected components with an outer loop

A connected component is a group of nodes where every node can reach every other node, and no node outside the group is reachable.

A single BFS or DFS traversal only visits vertices within the same connected component. If a graph contains multiple isolated clusters, one traversal leaves other components unvisited.

Counting connected components

Step 1 of 7

012345
count
0
Six vertices in three separate groups. The outer loop will look at vertices 0 to 5 in order, and count starts at 0.

Example 1 · Brute force: search from every vertex, O(V * (V + E)) time, O(V) space

Main.javaJava
import java.util.*;
public class Main {    static List<List<Integer>> adj = new ArrayList<>();
    static void reach(int u, boolean[] seen) {        seen[u] = true;        for (int v : adj.get(u)) if (!seen[v]) reach(v, seen);    }
    public static void main(String[] args) {        int n = 6;        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        int[][] edges = {{0, 1}, {1, 2}, {3, 4}};        for (int[] e : edges) {            adj.get(e[0]).add(e[1]);            adj.get(e[1]).add(e[0]);        }        int count = 0;        for (int s = 0; s < n; s++) {            boolean[] seen = new boolean[n];              // a fresh search from every vertex            reach(s, seen);            boolean smallestInGroup = true;            for (int v = 0; v < s; v++) if (seen[v]) smallestInGroup = false;            if (smallestInGroup) count++;                 // count each group once, at its smallest vertex        }        System.out.println("components: " + count);    }}
Output
components: 3

What this code does

  • Every vertex starts its own full search, and the smallest vertex of each group is counted once.
  • Each search can cost O(V + E), and it runs V times, so the total is V * (V + E).
  • The optimal version shares one visited array between all searches, so every vertex and edge is handled once.

Example 2 · Optimal: one shared visited array, O(V + E) time, O(V) space

Main.javaJava
import java.util.*;
public class Main {    static int countComponents(int n, int[][] edges) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        for (int[] e : edges) {            adj.get(e[0]).add(e[1]);            adj.get(e[1]).add(e[0]);        }
        boolean[] vis = new boolean[n];        int count = 0;        for (int i = 0; i < n; i++) {            if (!vis[i]) {                count++;                dfs(i, adj, vis);            }        }        return count;    }
    static void dfs(int u, List<List<Integer>> adj, boolean[] vis) {        vis[u] = true;        for (int v : adj.get(u)) {            if (!vis[v]) dfs(v, adj, vis);        }    }
    public static void main(String[] args) {        int[][] edges = {{0, 1}, {1, 2}, {3, 4}};        System.out.println("Components count: " + countComponents(5, edges));    }}
Output
Components count: 2

What this code does

  • Vertices 0, 1, and 2 form the first component.
  • Vertices 3 and 4 form the second component.
  • The outer loop triggers DFS twice, yielding 2 total components.
  • It is faster because a vertex that was visited by an earlier traversal is skipped, so no vertex or edge is searched twice.

We count components by wrapping traversal in an outer loop over all vertices 0 to V - 1. Maintain a global boolean visited array. Whenever the loop encounters an unvisited vertex, increment the component counter by one. Then launch BFS or DFS from that vertex to mark all reachable nodes in that component. When the loop finishes, the counter holds the total component count in O(V + E) time.

Find the bug

Find the counting bug

Each snippet counts connected components. Tap the wrong line.

The code always prints 0.

Round 1 of 2

Component sizes and labeling nodes with component IDs

Many network clustering problems require measuring component sizes or labeling vertices by group. During each traversal, maintain a counter of visited vertices to compute the component size. Tracking the maximum size finds the largest connected cluster in the network.

Example 3 · Finding the Largest Component Size

Main.javaJava
import java.util.*;
public class Main {    static int largestComponent(int n, int[][] edges) {        List<List<Integer>> adj = new ArrayList<>();        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());        for (int[] e : edges) {            adj.get(e[0]).add(e[1]);            adj.get(e[1]).add(e[0]);        }
        boolean[] vis = new boolean[n];        int maxCluster = 0;        for (int i = 0; i < n; i++) {            if (!vis[i]) {                int size = dfsSize(i, adj, vis);                maxCluster = Math.max(maxCluster, size);            }        }        return maxCluster;    }
    static int dfsSize(int u, List<List<Integer>> adj, boolean[] vis) {        vis[u] = true;        int size = 1;        for (int v : adj.get(u)) {            if (!vis[v]) size += dfsSize(v, adj, vis);        }        return size;    }
    public static void main(String[] args) {        int[][] edges = {{0, 1}, {1, 2}, {2, 3}, {4, 5}};        System.out.println("Largest component size: " + largestComponent(6, edges));    }}
Output
Largest component size: 4

What this code does

  • Component {0, 1, 2, 3} contains 4 vertices.
  • Component {4, 5} contains 2 vertices.
  • The maximum size cluster is 4.

We can also assign a component ID to each vertex using an array componentId of size V. Every vertex in the first component receives ID 0, the next receives ID 1, and so forth. Querying whether two vertices u and v are connected simplifies to checking componentId[u] == componentId[v] in O(1) time.

Friend circles and real world cluster analysis

Social platforms analyze friend circles to recommend groups and suggest relevant content. A friend circle consists of individuals connected through direct or mutual friendships. If Alice knows Bob and Bob knows Charlie, all three belong to the same friend circle component.

Example 4 · Friend Circles from Adjacency Matrix

Main.javaJava
public class Main {    static int findCircleNum(int[][] isConnected) {        int n = isConnected.length;        boolean[] vis = new boolean[n];        int circles = 0;
        for (int i = 0; i < n; i++) {            if (!vis[i]) {                circles++;                dfs(i, isConnected, vis);            }        }        return circles;    }
    static void dfs(int u, int[][] isConnected, boolean[] vis) {        vis[u] = true;        for (int v = 0; v < isConnected.length; v++) {            if (isConnected[u][v] == 1 && !vis[v]) {                dfs(v, isConnected, vis);            }        }    }
    public static void main(String[] args) {        int[][] matrix = {            {1, 1, 0},            {1, 1, 0},            {0, 0, 1}        };        System.out.println("Friend circles: " + findCircleNum(matrix));    }}
Output
Friend circles: 2

What this code does

  • Persons 0 and 1 are mutual friends, forming circle 1.
  • Person 2 has no friends, forming circle 2.
  • Total friend circles count is 2.

Epidemiologists model disease transmission clusters as connected components. Computer network monitoring tools detect network partitions when component count rises above one.

Next step

Check your understanding

10 quick questions