You have a graph of n
nodes. You are given an integer n
and an array edges
where edges[i] = [ai, bi]
indicates that there is an edge between ai
and bi
in the graph.
Return the number of connected components in the graph.
Example 1:
Input: n = 5, edges = [[0,1],[1,2],[3,4]] Output: 2
Example 2:
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]] Output: 1
Constraints:
1 <= n <= 2000
1 <= edges.length <= 5000
edges[i].length == 2
0 <= ai <= bi < n
ai != bi
- There are no repeated edges.
一道用于并查集Union Find的入门上手题,解法跟Leetcode200. Number of Islands几乎一模一样,套用Union Find模板几乎不要改动。对每条边的两个顶点进行合并,最后集合个数就是答案。
class UnionFind:
def __init__(self, n):
self.parent = list(range(0, n))
self.size = [1] * n
self.cnt = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def merge(self, x, y):
px, py = self.find(x), self.find(y)
if px == py:
return
if self.size[px] > self.size[py] :
self.parent[py] = px
self.size[px] += self.size[py]
else:
self.parent[px] = py
self.size[py] += self.size[px]
self.cnt -= 1
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
uf = UnionFind(n)
for e in edges :
uf.merge(e[0], e[1])
return uf.cnt
可以在刷LeetCode 684. Redundant Connection之前先刷一遍这道题。