1. 題目
給定編號從 0 到 n-1 的 n 個節點和一個無向邊列表(每條邊都是一對節點),請編寫一個函數來計算無向圖中連通分量的數目。
示例 1:
輸入: n = 5 和 edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
輸出: 2
示例 2:
輸入: n = 5 和 edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
0 4
| |
1 --- 2 --- 3
輸出: 1
注意:
你可以假設在 edges 中不會出現重複的邊。
而且由於所以的邊都是無向邊,[0, 1] 與 [1, 0] 相同,所以它們不會同時在 edges 中出現。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph 著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2. 解題
參考:並查集
class dsu
{
public:
vector<int> f;
dsu(int n)
{
f = vector<int>(n);
for(int i = 0; i < n; ++i)
f[i] = i;
}
void merge(int a, int b)
{
int fa = find(a);
int fb = find(b);
f[fa] = fb;
}
int find(int a)
{
int origin = a;
while(a != f[a])
a = f[a];
return f[origin] = a;
}
int countUni()
{
int count = 0;
for(int i = 0; i < f.size(); ++i)
{
if(i == find(i))
count++;
}
return count;
}
};
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
dsu u(n);
for(auto& e : edges)
u.merge(e[0],e[1]);
return u.countUni();
}
};
32 ms 10.9 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公衆號(Michael阿明),一起加油、一起學習進步!