-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path547.cpp
More file actions
46 lines (45 loc) · 1.26 KB
/
Copy path547.cpp
File metadata and controls
46 lines (45 loc) · 1.26 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
vector<int> circle;
public:
int findCircleNum(vector<vector<int>> &M) {
int n = M.size();
if (n == 0)
return 0;
circle = vector<int>(n, 0);
vector<int> rank(n, 0);
for (int i = 0; i < n; ++i)
circle[i] = i;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (M[i][j] == 1) {
int x = UnionFind(i);
int y = UnionFind(j);
if (circle[y] == x)
continue;
if (rank[x] > rank[y])
circle[y] = x;
else {
circle[x] = y;
if (rank[x] == rank[y])
++rank[y];
}
}
}
}
unordered_set<int> s;
for (int i = 0; i < n; ++i)
s.insert(UnionFind(circle[i]));
return s.size();
}
int UnionFind(int i) {
int root = i;
while (circle[root] != root)
root = circle[root];
while (i != root) {
int p = circle[i];
circle[i] = root;
i = p;
}
return circle[i];
}
};