算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 无向图中连通分量的数目,我们先来看题面:​https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph/​

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

给定编号从 0 到 n-1 的 n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连通分量的数目。


示例


​LeetCode刷题实战323:无向图中连通分量的数目_无向图

解题

题目可以转化为用并查集求一共有多少个老大的问题。

class Solution {
public:
//找每一个顶点的老大
int find_father(vector<int> &f, int i){
while(i!=f[i]){
i=f[i];
}
return i;
}

int countComponents(int n, vector<vector<int>>& edges) {
vector<int>f(n);
//将每一个顶点单独分成一组
for(int i=0; i<n; ++i){
f[i]=i;
}
//进行同一组的顶点的合并
for(auto x:edges){
int p=find_father(f, x[0]);
int q=find_father(f, x[1]);
if(p==q) continue;
else f[p]=q;
}
//找一共有多少个不同的老大
unordered_set<int>s;
for(int i=0; i<f.size(); ++i){
s.insert(find_father(f, i));
}
return s.size();
}
};

 ​​

​LeetCode刷题实战323:无向图中连通分量的数目_无向图_02