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

Constraints

Example

Input
n = 6, edges = [[0, 2], [2, 4], [1, 5]]
Output
3

Solve it

More in Union-Find

All algorithm problems