题目链接:https://leetcode.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.
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
.
思路: 为每一个结点设置一个父结点, 初始为本身. 如果一条边的最终父结点相同, 则说明他们是联通的, 否则就将第二个结点的最终父结点设置为第一个结点的最终父结点.
这样初始总共有n个不联通的结点, 每次新添加一条边, 如果他们最终父结点不想同, 则说明减少一个不联通的点.
代码如下:
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<int> par(n);
for(int i =0; i < n; i++) par[i] = i;
for(auto val: edges)
{
int par1 = val.first, par2 = val.second;
while(par[par1] != par1) par1 = par[par1];
while(par[par2] != par2) par2 = par[par2];
if(par1 != par2) par[par2] = par1, n--;
}
return n;
}
};