0%

323. Number of Connected Components in an Undirected Graph

union-find O(n) time O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
int countComponents(int n, vector<pair<int, int>>& edges) {
parent.resize(n);
iota(begin(parent), end(parent), 0);
res = n;
for (const auto &e : edges) {
merge(e.first, e.second);
}
return res;
}

int find(int x) {
while (x != parent[x]) {
x = parent[x] = parent[parent[x]];
}
return x;
}

void merge(int x, int y) {
int px = find(x);
int py = find(y);
if (px != py) {
parent[px] = py;
--res;
}
}

vector<int> parent;
int res;
};