Skip to content

Commit d2768b9

Browse files
authored
Create friend-circles.cpp
1 parent 9f10878 commit d2768b9

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

C++/friend-circles.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int findCircleNum(vector<vector<int>>& M) {
7+
UnionFind circles(M.size());
8+
for (int i = 0; i < M.size(); ++i) {
9+
for (int j = 0; j < M[i].size(); ++j) {
10+
if (M[i][j] && i != j) {
11+
circles.union_set(i, j);
12+
}
13+
}
14+
}
15+
return circles.size();
16+
}
17+
18+
private:
19+
class UnionFind {
20+
public:
21+
UnionFind(const int n) : set_(n), count_(n) {
22+
iota(set_.begin(), set_.end(), 0);
23+
}
24+
25+
int find_set(const int x) {
26+
if (set_[x] != x) {
27+
set_[x] = find_set(set_[x]); // Path compression.
28+
}
29+
return set_[x];
30+
}
31+
32+
void union_set(const int x, const int y) {
33+
int x_root = find_set(x), y_root = find_set(y);
34+
if (x_root != y_root) {
35+
set_[min(x_root, y_root)] = max(x_root, y_root);
36+
--count_;
37+
}
38+
}
39+
40+
int size() const {
41+
return count_;
42+
}
43+
44+
private:
45+
vector<int> set_;
46+
int count_;
47+
};
48+
};

0 commit comments

Comments
 (0)