323. Number of Connected Components in an Undirected Graph
0 3
| |
1 --- 2 4 0 4
| |
1 --- 2 --- 3class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
if(n == 0) return n; // need to manually check this case as array length > 0,
// which is different from Java
int res = n; int roots [n];
for(auto & i: roots) i = -1;
for(pair<int,int> p : edges){
int roota = find(roots, p.first);
int rootb = find(roots, p.second);
if(roota != rootb) {
// union
roots[roota] = rootb;
res--;
}
}
return res;
}
int find(int roots [], int v){
while(roots[v] != -1) v = roots[v];
return v;
}
};Last updated
Was this helpful?