[Leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告
来源:互联网 发布:js动态创建对象 编辑:程序博客网 时间:2024/06/06 02:05
题目:
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
.
思路:
一道难度适中的Union-Find题目。这类题目也有套路:首先为每个顶点初始化一个单独的集合;然后遍历,每次遇到一个边,就把边的两个顶点所属的集合进行合并,同时总的连通图数量减1。注意判断两个顶点是否属于同一个集合的经典代码,个人感觉应该背下来^_^。
这道题目用BFS和DFS也可以求解,但代码要相对复杂一些。
代码:
class Solution {public: int countComponents(int n, vector<pair<int, int>>& edges) { vector<int> parents(n); for (int i = 0; i < n; ++i) { parents[i] = i; } int ret = n; for (int i = 0; i < edges.size(); ++i) { int par1 = edges[i].first, par2 = edges[i].second; while (par1 != parents[par1]) { par1 = parents[par1]; } while (par2 != parents[par2]) { par2 = parents[par2]; } if (par1 != par2) { parents[par2] = par1; --ret; } } return ret; }};
阅读全文
0 0
- [leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告
- [Leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告
- LeetCode 323. Number of Connected Components in an Undirected Graph
- Leetcode 323. Number of Connected Components in an Undirected Graph
- LeetCode 323. Number of Connected Components in an Undirected Graph
- LeetCode 323. Number of Connected Components in an Undirected Graph
- Leetcode 323. Number of Connected Components in an Undirected Graph
- leetcode Number of Connected Components in an Undirected Graph
- 323. Number of Connected Components in an Undirected Graph
- LeetCode 323. Number of Connected Components in an Undirected Graph(连通分量)
- [leetcode323]Number of Connected Components in an Undirected Graph
- Number of Connected Components in an Undirected Graph
- No323. Number of Connected Components in an Undirected Graph
- leetcode323. Number of Connected Components in an Undirected Graph
- Number of Connected Components in an Undirected Graph 无向图中的连通区域的个数
- Sicily 1002. connected components in undirected graph
- Connected Component in Undirected Graph
- connect components in undirected graph
- R 学习
- 5.数组
- 如何安装python的第三方扩展库
- CentOS 6.5下Redis安装部署配置指南
- 计算日期间隔
- [Leetcode] 323. Number of Connected Components in an Undirected Graph 解题报告
- 可视化日历的实现
- continue结束本次循环和break跳出当前循环
- 1696:逆波兰表达式
- R 学习
- 循环的实例练习
- 英伟达Volta解读:专为深度学习而生的Tensor Core是什么?
- mysql for update行级锁
- 禁止用户查询某个列