947. Most Stones Removed with Same Row or Column

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
61
62
63
64
65
66
67
68
69
class UnionFind{
private:
vector<int> parent, size;
int count;
public:
UnionFind(int n){
parent = vector<int>(n);
size = vector<int>(n);
count = n;
for(int i=0;i<n;++i){
parent[i] = i;
size[i] = 1;
}
}
bool connect(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
return pRoot == qRoot;
}
int find(int x){
while(parent[x]!=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]){
parent[qRoot] = parent[pRoot];
size[pRoot] += size[qRoot];
}
else{
parent[pRoot] = parent[qRoot];
size[qRoot] += size[pRoot];
}

}
void print(){
// for debug
for(int p:parent) cout<<p<<" ";
cout<<endl;
for(int s:size) cout<<s<<" ";
cout<<endl;
}
};
class Solution {
public:
int removeStones(vector<vector<int>>& stones) {
int n = stones.size();
UnionFind * uf = new UnionFind(n);
for(int i= 0;i<n;++i){
for(int j = i+1;j<n ; ++j){
if(stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]){
uf->unionSet(i,j);
}
}
}
// uf->print();
unordered_set<int> s;
for(int i=0;i<n;++i){
s.insert(uf->find(i));
}
return n - s.size() ;

}
};