Number of Connected Components in an Undirected Graph — Union-Find
Count how many separate clusters a set of linked machines forms, counting each isolated machine as its own cluster.
Union-Find · Easy
The problem
A campus has n servers labelled 0 to n-1 and a list of cables between them. Count how many separate clusters of servers there are, where servers in a cluster can reach each other over cables.
The story
A campus has 1 to 10 servers labelled 0 to n-1 and up to 12 cables between them. Servers that can reach each other over cables form a cluster, and a server with no cables is a cluster of its own. Count the clusters.
What to return
- Return the number of connected components. A node with no edges counts as a component of its own.
Constraints
- 1 <= n <= 10
- 0 <= edges.length <= 12
- edges[i] = [u, v] with 0 <= u, v < n and u != v
- no pair of nodes is listed twice (in either direction)
Example
- Input
n = 6, edges = [[0, 2], [2, 4], [1, 5]]- Output
3