Number of Connected Components in an Undirected Graph
Examples
Example 1:
Input: n=3
edges=[[0,1], [0,2]]
Output: 1
Example 2:
Input: n=6
edges=[[0,1], [1,2], [2,3], [4,5]]
Output: 2
Example 1:
Input: n=3
edges=[[0,1], [0,2]]
Output: 1
Example 2:
Input: n=6
edges=[[0,1], [1,2], [2,3], [4,5]]
Output: 2
There is an undirected graph with n nodes. There is also an edges array, where edges[i] = [a, b] means that there is an edge between node a and node b in the graph.
The nodes are numbered from 0 to n - 1.
Return the total number of connected components in that graph.
1 <= n <= 1000 <= edges.length <= n * (n - 1) / 2Use Union-Find to group nodes. Start with each node as its own component. For every edge, union the endpoints; if they were in different sets, reduce the component count. The final count is the answer.
Union-Find merges exactly the nodes that are connected by some path. Each successful union reduces the number of connected components by one. After processing all edges, the remaining set count equals the number of connected components.
O(n + e)O(n)class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
parent = list(range(n))
rank = [0] * n
count = n
def find(x: int) -> int:
while x != parent[x]:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a: int, b: int) -> bool:
ra, rb = find(a), find(b)
if ra == rb:
return False
if rank[ra] < rank[rb]:
parent[ra] = rb
elif rank[ra] > rank[rb]:
parent[rb] = ra
else:
parent[rb] = ra
rank[ra] += 1
return True
for a, b in edges:
if union(a, b):
count -= 1
return count