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();
}
};

最新文章

  1. JavaScript模仿块级作用域
  2. ORM框架示例及查询测试,上首页修改版(11种框架)
  3. QMessageBox 使用方法
  4. crm 4 IFRAME 元素隐藏
  5. UVA 10497 - Sweet Child Makes Trouble 高精度DP
  6. 找不到对应的webservice配置参数[ProcessService]
  7. 用maven进行测试
  8. Hibernate学习笔记--------3.缓存
  9. 基于GBT28181:SIP协议组件开发-----------第三篇SIP注册流程分析实现
  10. Linux中的盘符问题
  11. maven项目部署到Repository(Nexus)
  12. SVD分解技术详解
  13. html5中让页面缩放的4种方法
  14. MongoDB副本集及C#程序的连接配置
  15. 对lua中__newindex的理解
  16. freemarker demo
  17. scrapy初探(一)-斗鱼TV直播信息抓取
  18. Java入门:一些初学者需要掌握的基础算法程序——二分查找
  19. Gulp安装笔记
  20. Vscode 修改为中文语言

热门文章

  1. (原)Unreal Shader模块(一): 着色创建
  2. 决策树之CART算法
  3. 1024Studio官网
  4. 【Android】Android中期项目设计题目-界面设计小作业-提交截止时间2016.4.8
  5. CF 1103B Game with modulo
  6. [bzoj] 1043 下落的圆盘 || 圆上的“线段覆盖”
  7. Codeforces 585D Lizard Era: Beginning | 折半搜索
  8. bzoj4386 Wycieczki
  9. CSU 2136 ——湖南多校对抗赛 I
  10. AI人工客服开发 小程序智能客服 智能客服微信小程序 智能客服系统怎么做 如何设计智能客服系统