Algo-Sim › Graph Traversal

Number of Connected Components (DFS)

Medium · Graph Traversal · step through it in Java, Python and C++ on your own input

Count the pieces of an undirected graph: every node no DFS has reached yet starts a new component.

Problem

Given n nodes labelled 0..n − 1 and a list of undirected edges, return the number of connected components: groups of nodes that are joined to each other by paths and to nothing else.

Constraints

Edge cases to test

Follow-up questions

What if edges arrive over time?
Union-find keeps the count as edges are added: near O(1) per edge.
What if edges can also be deleted?
Much harder: process offline in reverse (add edges back) with union-find, or use a dynamic connectivity structure.

Solution

Java

public 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[] visited = new boolean[n];
    int components = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) {
            components++;
            dfs(adj, i, visited);
        }
    }
    return components;
}

private void dfs(List<List<Integer>> adj, int node, boolean[] visited) {
    visited[node] = true;
    for (int next : adj.get(node)) {
        if (!visited[next]) dfs(adj, next, visited);
    }
}

Python

def count_components(n, edges):
    adj = [[] for _ in range(n)]
    for a, b in edges:
        adj[a].append(b)
        adj[b].append(a)
    visited = [False] * n

    def dfs(node):
        visited[node] = True
        for nxt in adj[node]:
            if not visited[nxt]:
                dfs(nxt)

    components = 0
    for i in range(n):
        if not visited[i]:
            components += 1
            dfs(i)
    return components

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int countComponents(int n, vector<vector<int>> &edges) {
        vector<vector<int>> adj = {};
        for (int i = 0; i < n; i++)
            adj.push_back({});
        for (vector<int> &e : edges) {
            adj[e[0]].push_back(e[1]);
            adj[e[1]].push_back(e[0]);
        }
        vector<bool> visited = vector<bool>(n);
        int components = 0;
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                components++;
                dfs(adj, i, visited);
            }
        }
        return components;
    }

    void dfs(vector<vector<int>> &adj, int node, vector<bool> &visited) {
        visited[node] = true;
        for (int next : adj[node]) {
            if (!visited[next])
                dfs(adj, next, visited);
        }
    }
};

More Graph Traversal problems