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:
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
Output: 2
Example 2:
Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
0 4
| |
1 --- 2 --- 3
Output: 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.
思路:
设置一个roots, 遍历所有edge,如果不连接则连上,并且将n–。如果已经连上了则掠过。
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
vector<int> roots(n, -1);
int result = n;
for (auto edge: edges){
int x = find(roots, edge.first);
int y = find(roots, edge.second);
if (x == y) continue;
else {
roots[x] = y;
result --;
}
}
return result;
}
int find(vector<int> & roots, int i){
while (roots[i] != -1){
i = roots[i];
}
return i;
}
};
weighedUnion and path compression (模版)
class Solution {
public:
int countComponents(int n, vector<vector<int>>& edges) {
vector<int> root(n, -1);
for (int i = 0; i < n; i++) root[i] = i;
vector<int> size(n , 1);
int result = n;
for (auto e: edges) {
if (weightedUnion(root, size, e[0], e[1])){
result--;
}
}
return result;
}
int unionHelper(vector<int> & root, int i) {
while (root[i] != i) {
root[i] = root[root[i]];
i = root[i];
}
return i;
}
bool weightedUnion(vector<int> & root, vector<int> & size, int x, int y) {
int parent1 = unionHelper(root, x);
int parent2 = unionHelper(root, y);
if (parent1 != parent2) {
if (size[parent1] >= size[parent2]) {
root[parent2] = parent1;
size[parent1] = size[parent2] += size[parent1];
}
else {
root[parent1] = parent2;
size[parent2] = size[parent1] += size[parent2];
}
return true;
}
return false;
}
};
grandyang: http://www.cnblogs.com/grandyang/p/5166356.html
思路:
和200. number of islands 很相似,是一维的版本。用dfs遍历,将遍历过的地方mark。循环发起dfs,但只从之前没有遍历过的点。每发起一次计数++。最后返回计数即为结果。
class Solution {
public:
int countComponents(int n, vector<pair<int, int> >& edges) {
int res = 0;
vector<vector<int> > g(n);
vector<bool> v(n, false);
for (auto a : edges) {
g[a.first].push_back(a.second);
g[a.second].push_back(a.first);
}
for (int i = 0; i < n; ++i) {
if (!v[i]) {
++res;
dfs(g, v, i);
}
}
return res;
}
void dfs(vector<vector<int> > &g, vector<bool> &v, int i) {
if (v[i]) return;
v[i] = true;
for (int j = 0; j < g[i].size(); ++j) {
dfs(g, v, g[i][j]);
}
}
};