import java.util.HashMap;
class Solution {
public static HashMap<Integer, Integer> row = new HashMap<>();
public static HashMap<Integer, Integer> col = new HashMap<>();
public static int MAXN = 1001;
public static int[] f = new int[MAXN];
public static int set = MAXN;
public static void build(int n) {
row.clear();
col.clear();
for (int i = 0; i < n; i++) {
f[i] = i;
}
set = n;
}
public static int find(int i) {
if (f[i] != i) {
f[i] = find(f[i]);
}
return f[i];
}
public static void union(int i, int j) {
int f_i = find(i);
int f_j = find(j);
if (f_i != f_j) {
f[f_i] = f_j;
set--;
}
}
public int removeStones(int[][] stones) {
int n = stones.length;
build(n);
for (int i = 0; i < n; i++) {
if (row.containsKey(stones[i][0])) {
// 当前行已经有数了。可以合并。
union(i, row.get(stones[i][0]));
} else {
row.put(stones[i][0], i);
}
if (col.containsKey(stones[i][1])) {
union(i, col.get(stones[i][1]));
} else {
col.put(stones[i][1], i);
}
}
return n - set;
}
}