Connected Components
DSA · Graphssyntax
Run BFS or DFS from each unvisited node.
Each run discovers one connected component.
Count the number of runs = number of components.example
// JavaScript
function countComponents(n, edges) {
const graph = new Map();
for (let i = 0; i < n; i++) graph.set(i, []);
for (const [u, v] of edges) {
graph.get(u).push(v);
graph.get(v).push(u);
}
const visited = new Set();
let components = 0;
for (let i = 0; i < n; i++) {
if (!visited.has(i)) {
components++;
const queue = [i];
visited.add(i);
while (queue.length) {
const node = queue.shift();
for (const nb of graph.get(node)) {
if (!visited.has(nb)) {
visited.add(nb);
queue.push(nb);
}
}
}
}
}
return components;
}
# Python
def count_components(n, edges):
from collections import defaultdict, deque
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
visited = set()
components = 0
for i in range(n):
if i not in visited:
components += 1
queue = deque([i])
visited.add(i)
while queue:
node = queue.popleft()
for nb in graph[node]:
if nb not in visited:
visited.add(nb)
queue.append(nb)
return componentsoutput
n=5, edges=[[0,1],[1,2],[3,4]] → 2 components ({0,1,2} and {3,4})Note Time O(V + E), Space O(V). Alternative: Union-Find achieves the same result and is better for dynamic connectivity. This pattern is the basis for 'number of islands' and 'number of provinces' problems.