码迷,mamicode.com
首页 > 其他好文 > 详细

Number of Connected Components in an Undirected Graph -- LeetCode

时间:2016-08-19 07:29:23      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

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 class Solution {
 2 public:
 3     int getFather(vector<int>& father, int i) {
 4         if (father[i] == i) return i;
 5         father[i] = getFather(father, father[i]);
 6         return father[i];
 7     }
 8     void merge(vector<int>& father, int i, int j) {
 9         int fatherI = getFather(father, i);
10         int fatherJ = getFather(father, j);
11         father[fatherJ] = fatherI;
12     }
13     int countComponents(int n, vector<pair<int, int>>& edges) {
14         vector<int> father;
15         for (int i = 0; i < n; i++) father.push_back(i);
16         for (int i = 0, n = edges.size(); i < n; i++)
17             merge(father, get<0>(edges[i]), get<1>(edges[i]));
18         unordered_set<int> unions;
19         for (int i = 0; i < n; i++) unions.insert(getFather(father, i));
20         return unions.size();
21     }
22 };

 

Number of Connected Components in an Undirected Graph -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5786148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!