547. Number of Provinces

problem

solution

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class UnionFind{
public:
vector<int> size, parent;
int count;
UnionFind(int cap){
parent = vector<int>(cap, 0);
size = vector<int>(cap, 1);
count = cap;
for(int i=0;i<cap;++i){
parent[i] = i;
}
}
bool connect(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
return pRoot == qRoot;
}
int find(int x){
while(x!=parent[x]){
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
void unionSet(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
if(pRoot == qRoot) return ;
if(size[pRoot] >= size[qRoot]){
size[pRoot] +=size[qRoot];
parent[qRoot] = parent[pRoot];
}
else{
size[qRoot] +=size[pRoot];
parent[pRoot] = parent[qRoot];
}
}
int getCount(){
int ret = 0;
for(int i=0;i<count;++i){
if(parent[i] == i) ret++;
}
return ret;
}
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
UnionFind *uf = new UnionFind(n);
for(int i=0;i<n;++i){
for(int j=i+1;j<n;++j){
if(isConnected[i][j] == 1) uf->unionSet(i,j);
}
}

return uf->getCount();
}
};