题目地址:
https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
给出 m m m条边,求 n n n个点的无向图的连通分量。
并查集。开一个点数为 n n n的并查集,并对每条边的两个端点做union操作,最后返回一下有多少个连通块即可。代码如下:
class Solution {
public:
vector<int> p;
int countComponents(int n, vector<vector<int>>& edges) {
p.resize(n);
for (int i = 0; i < n; i++) p[i] = i;
int res = n;
auto merge = [&](int x, int y) {
int px = find(x), py = find(y);
if (px != py) p[px] = py, res--;
};
for (auto& e : edges) merge(e[0], e[1]);
return res;
}
int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }
};
时间复杂度 O ( m log ∗ n ) O(m\log^*n) O(mlog∗n),空间 O ( n ) O(n) O(n)。