-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode547.cpp
More file actions
37 lines (36 loc) · 830 Bytes
/
leetcode547.cpp
File metadata and controls
37 lines (36 loc) · 830 Bytes
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
class Solution {
private:
vector<int> father;
int count;
int find(int x) {
if(father[x] == x)
return x;
return father[x] = find(father[x]);
}
void connect(int x, int y) {
int fx = find(x);
int fy = find(y);
if(fx != fy) {
father[fx] = fy;
count--;
}
}
public:
int findCircleNum(vector<vector<int>>& M) {
if(M.size() == 0)
return 0;
int n = M.size();
count = n;
father.resize(n);
for(int i = 0; i < n; i++)
father[i] = i;
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(M[i][j] == 1) {
connect(i, j);
}
}
}
return count;
}
};