一、题目描述
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.
Example 1:
0 3 | | 1 --- 2 4
Given n = 5
and edges = [[0, 1], [1, 2], [3, 4]]
, return 2
.
Example 2:
0 4 | | 1 --- 2 --- 3
Given n = 5
and edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
, return 1
.
Note:
You can assume that no duplicate edges will appear in edges
. Since all edges are undirected, [0, 1]
is the same as [1, 0]
and thus will not appear together in edges
.
二、解题思路
使用并查集来解题,关于并查集的介绍,我强烈推荐一篇博客:http://blog.csdn.net/dellaserss/article/details/7724401 ,看完之后醍醐灌顶,以下代码就很好理解了,先把每个点的根设为自己,所以有n个独立不相连的点,然后根据每条边,对每条边的两个点进行寻根,如果一个点的根不是自己,则该点还不是根节点,所以继续寻根,找到一条边的两个顶点的根之后进行比较 ,如果不一样,则将一个的根设定为另一个,这样就将两部分连接起来了。
三、代码实现
public class Solution{
int countComponents(int n, vector<pair<int, int>>& edges){
vector<int> root(n);
int count = n;
for(int i=0;i<n;i++)
root[i]=i;
for(auto p:edges){
int p1=p.first,p2=p.second;
while(root[p1]!=p1) p1=root[p1];
while(root[p2]!=p2) p2=root[p2];
if(p1!=p2){
root[p2]=root[p1];
count--;
}
}
return count;
}
}