Skip to content

Commit f3ec9f2

Browse files
committed
Create number-of-connected-components-in-an-undirected-graph.cpp
1 parent 6d1159c commit f3ec9f2

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Time: O(nlog*n) ~= O(n), n is the length of the positions
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int countComponents(int n, vector<pair<int, int>>& edges) {
7+
UnionFind union_find(n);
8+
for (const auto& e : edges) {
9+
union_find.union_set(e.first, e.second);
10+
}
11+
return union_find.length();
12+
}
13+
14+
private:
15+
class UnionFind {
16+
public:
17+
UnionFind(const int n) : set(n) {
18+
iota(set.begin(), set.end(), 0);
19+
count_ = n;
20+
}
21+
22+
int find_set(int x) {
23+
if (set[x] != x) {
24+
set[x] = find_set(set[x]); // Path compression.
25+
}
26+
return set[x];
27+
}
28+
29+
void union_set(const int x, const int y) {
30+
int x_root = find_set(x), y_root = find_set(y);
31+
if (x_root != y_root) {
32+
set[min(x_root, y_root)] = max(x_root, y_root);
33+
--count_;
34+
}
35+
}
36+
37+
int length() const {
38+
return count_;
39+
}
40+
41+
private:
42+
vector<int> set;
43+
int count_;
44+
};
45+
};

0 commit comments

Comments
 (0)