c++
class Solution {
public:
class UnionSet {
public:
int *father, n;
UnionSet(int n) : n(n) {
father = new int[n + 1];
for (int i = 0; i <= n; i++) {
father[i] = i;
}
}
int find(int x) {
return father[x] = (father[x] == x ? x : find(father[x]));
}
void merge(int a, int b) {
father[find(a)] = find(b);
return ;
}
};
int removeStones(vector<vector<int>>& stones) {
UnionSet u(stones.size());
unordered_map<int, int> map_x, map_y;
for (int i = 0; i < stones.size(); i++) {
if (map_x.find(stones[i][0]) != map_x.end()) {
u.merge(i, map_x[stones[i][0]]);
}
if (map_y.find(stones[i][1]) != map_y.end()) {
u.merge(i, map_y[stones[i][1]]);
}
map_x[stones[i][0]] = i;
map_y[stones[i][1]] = i;
}
int cnt = 0;
for (int i = 0; i < stones.size(); i++) {
if (u.find(i) == i) cnt++;
}
return stones.size() - cnt;
}
};
js
class UnionSet {
constructor(n) {
this.father = new Array(n);
for (var i = 0; i < n; i++) this.father[i] = i;
}
find(x) {
return this.father[x] = (this.father[x] == x ? x : this.find(this.father[x]));
}
merge(a, b) {
this.father[this.find(a)] = this.find(b);
}
};
var removeStones = function(stones) {
var u = new UnionSet(stones.length);
var map_x = new Map(), map_y = new Map();
for (var i = 0; i < stones.length; i++) {
if (map_x.has(stones[i][0])) u.merge(i, map_x.get(stones[i][0]));
if (map_y.has(stones[i][1])) u.merge(i, map_y.get(stones[i][1]));
map_x.set(stones[i][0], i);
map_y.set(stones[i][1], i);
}
var cnt = 0;
for (var i = 0; i < stones.length; i++) {
if (u.find(i) == i) cnt++;
}
return stones.length - cnt;
};