Count Connected Components
Medium graphs · union-find
Description
Constraints
1 <= n <= 100000
Examples
Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
Hints (1)
- Flood fill each unvisited node with DFS or BFS and count the floods.
Solutions
DFS flood fill. · Time O(V+E) · Space O(V+E)
func countComponents(n int, edges [][]int) int {
adj := make([][]int, n)
for _, e := range edges {
adj[e[0]] = append(adj[e[0]], e[1])
adj[e[1]] = append(adj[e[1]], e[0])
}
seen := make([]bool, n)
count := 0
for s := 0; s < n; s++ {
if seen[s] {
continue
}
count++
stack := []int{s}
for len(stack) > 0 {
u := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if seen[u] {
continue
}
seen[u] = true
for _, v := range adj[u] {
if !seen[v] {
stack = append(stack, v)
}
}
}
}
return count
}
DFS flood fill. · Time O(V+E) · Space O(V+E)
function countComponents(n, edges) {
const adj = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); }
const seen = new Array(n).fill(false);
let count = 0;
for (let s = 0; s < n; s++) {
if (seen[s]) continue;
count++;
const stack = [s];
while (stack.length) {
const u = stack.pop();
if (seen[u]) continue;
seen[u] = true;
for (const v of adj[u]) if (!seen[v]) stack.push(v);
}
}
return count;
}
DFS flood fill. · Time O(V+E) · Space O(V+E)
function countComponents($n, $edges) {
$adj = array_fill(0, $n, []);
foreach ($edges as $e) { $adj[$e[0]][] = $e[1]; $adj[$e[1]][] = $e[0]; }
$seen = array_fill(0, $n, false); $count = 0;
for ($s = 0; $s < $n; $s++) {
if ($seen[$s]) continue;
$count++; $stack = [$s];
while ($stack) {
$u = array_pop($stack);
if ($seen[$u]) continue;
$seen[$u] = true;
foreach ($adj[$u] as $v) { if (!$seen[$v]) $stack[] = $v; }
}
}
return $count;
}
DFS flood fill. · Time O(V+E) · Space O(V+E)
def countComponents(n, edges):
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
seen = [False] * n
count = 0
for s in range(n):
if seen[s]:
continue
count += 1
stack = [s]
while stack:
u = stack.pop()
if seen[u]:
continue
seen[u] = True
for v in adj[u]:
if not seen[v]:
stack.append(v)
return count
DFS flood fill. · Time O(V+E) · Space O(V+E)
function countComponents(n: number, edges: number[][]): number {
const adj: number[][] = Array.from({ length: n }, () => []);
for (const [u, v] of edges) { adj[u].push(v); adj[v].push(u); }
const seen = new Array(n).fill(false);
let count = 0;
for (let s = 0; s < n; s++) {
if (seen[s]) continue;
count++;
const stack = [s];
while (stack.length) {
const u = stack.pop()!;
if (seen[u]) continue;
seen[u] = true;
for (const v of adj[u]) if (!seen[v]) stack.push(v);
}
}
return count;
}
Create a free account to submit solutions, track progress and save problems.
Create account