[leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告
2016-03-13 06:48
393 查看
题目链接:https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
Given
Example 1:
Given
Example 2:
Given
Note:
You can assume that no duplicate edges will appear in
思路: 为每一个结点设置一个父结点, 初始为本身. 如果一条边的最终父结点相同, 则说明他们是联通的, 否则就将第二个结点的最终父结点设置为第一个结点的最终父结点.
这样初始总共有n个不联通的结点, 每次新添加一条边, 如果他们最终父结点不想同, 则说明减少一个不联通的点.
代码如下:
Given
nnodes labeled from
0to
n - 1and 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 = 5and
edges = [[0, 1], [1, 2], [3, 4]], return
2.
Example 2:
0 4 | | 1 --- 2 --- 3
Given
n = 5and
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> parent(n); int ans = n; for(int i = 0; i< n; i++) parent[i] = i; for(auto val: edges) { int pa = val.first, pb = val.second; while(parent[pa] != pa) pa = parent[pa]; while(parent[pb] != pb) pb = parent[pb]; if(pa != pb) { parent[pb] = pa; ans--; } } return ans; } };参考: https://leetcode.com/discuss/76519/similar-to-number-of-islands-ii-with-a-findroot-function
相关文章推荐
- bzoj 1507: [NOI2003]Editor
- bzoj 1503: [NOI2004]郁闷的出纳员
- bzoj 1497: [NOI2006]最大获利
- 第一次
- Eclipse快捷键
- bzoj 1492: [NOI2007]货币兑换Cash
- bzoj 1491: [NOI2007]社交网络
- 71.双向最短路径:聚会
- bzoj 1483: [HNOI2009]梦幻布丁
- 71.双向最短路径:聚会
- 71.双向最短路径:聚会
- [leetcode] 245. Shortest Word Distance III 解题报告
- bzoj 1433: [ZJOI2009]假期的宿舍
- bzoj 1432: [ZJOI2009]Function
- bzoj 1415: [Noi2005]聪聪和可可
- bzoj 1412: [ZJOI2009]狼和羊的故事
- Palindrome 系列
- 谷歌人机大战与新时代的来临
- 工厂模式之小结与区别(6)
- 抽象工厂模式(5)