Number of Connected Components in an Undirected Graph -- LeetCode
2024-08-29 17:16:20
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:
| |
---
Given n = 5
and edges = [[0, 1], [1, 2], [3, 4]]
, return 2
.
Example 2:
| |
--- ---
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)
class Solution {
public:
int getFather(vector<int>& father, int i) {
if (father[i] == i) return i;
father[i] = getFather(father, father[i]);
return father[i];
}
void merge(vector<int>& father, int i, int j) {
int fatherI = getFather(father, i);
int fatherJ = getFather(father, j);
father[fatherJ] = fatherI;
}
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<int> father;
for (int i = ; i < n; i++) father.push_back(i);
for (int i = , n = edges.size(); i < n; i++)
merge(father, get<>(edges[i]), get<>(edges[i]));
unordered_set<int> unions;
for (int i = ; i < n; i++) unions.insert(getFather(father, i));
return unions.size();
}
};
最新文章
- JavaScript模仿块级作用域
- ORM框架示例及查询测试,上首页修改版(11种框架)
- QMessageBox 使用方法
- crm 4 IFRAME 元素隐藏
- UVA 10497 - Sweet Child Makes Trouble 高精度DP
- 找不到对应的webservice配置参数[ProcessService]
- 用maven进行测试
- Hibernate学习笔记--------3.缓存
- 基于GBT28181:SIP协议组件开发-----------第三篇SIP注册流程分析实现
- Linux中的盘符问题
- maven项目部署到Repository(Nexus)
- SVD分解技术详解
- html5中让页面缩放的4种方法
- MongoDB副本集及C#程序的连接配置
- 对lua中__newindex的理解
- freemarker demo
- scrapy初探(一)-斗鱼TV直播信息抓取
- Java入门:一些初学者需要掌握的基础算法程序——二分查找
- Gulp安装笔记
- Vscode 修改为中文语言
热门文章
- (原)Unreal Shader模块(一): 着色创建
- 决策树之CART算法
- 1024Studio官网
- 【Android】Android中期项目设计题目-界面设计小作业-提交截止时间2016.4.8
- CF 1103B Game with modulo
- [bzoj] 1043 下落的圆盘 || 圆上的“线段覆盖”
- Codeforces 585D Lizard Era: Beginning | 折半搜索
- bzoj4386 Wycieczki
- CSU 2136 ——湖南多校对抗赛 I
- AI人工客服开发 小程序智能客服 	智能客服微信小程序 智能客服系统怎么做 	如何设计智能客服系统