classSolution {publicintremoveStones(int[][] stones) {int[] parent =newint[20000];for (int i =0; i <20000; ++i) parent[i] = i;int N =stones.length;// build unionsfor (int[] stone : stones) {union(stone[0], stone[1] +10000, parent); }Set<Integer> seen =newHashSet();for (int[] stone : stones) {// One component has one top parentseen.add(find(stone[0], parent)); }// Now we can remove everything except one stone from each componentreturn N -seen.size(); }publicintfind(int x,int[] parent) {if (parent[x] != x) parent[x] =find(parent[x], parent);return parent[x]; }publicvoidunion(int x,int y,int[] parent) { parent[find(x, parent)] =find(y, parent); }}