On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
Now, a move consists of removing a stone that shares a column or row with another stone on the grid.
What is the largest possible number of moves we can make?
Example 1:
Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
Output: 5
Example 2:
Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
Output: 3
Example 3:
Input: stones = [[0,0]]
Output: 0
Note:
1 <= stones.length <= 1000
0 <= stones[i][j] < 10000
class Solution {
public int removeStones(int[][] stones) {
HashMap<Integer, Integer> unionFind = new HashMap<>();
for (int i = 0; i < stones.length; i++) {
unionFind.put(i, i);
}
for (int i = 0; i < stones.length; i++) {
for (int j = 0; j < stones.length; j++) {
if(i==j)continue;
if (stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
int iRoot = findRoot(i, unionFind);
int jRoot = findRoot(j, unionFind);
if (iRoot != jRoot) {
if (iRoot < jRoot) unionFind.put(jRoot, iRoot);
else unionFind.put(iRoot, jRoot);
}
}
}
}
// Integer a = 11;
// Integer b = 11;
// System.out.println(a == b);
int group = 0;
// 不知道为什么用下面keySet的方法遍历就会错,而用i来遍历就不会错= = , 如果谁知道可以告诉我为什么
// for (Integer key : unionFind.keySet()) {
// if (key == 191) System.out.println(key + "+++" + (unionFind.get(key) == key));
// if (key == unionFind.get(key)) {
// System.out.println(key + " " + unionFind.get(key));
// group++;
// }
// }
for (int i = 0; i < stones.length; i++) {
if (i == unionFind.get(i)) {
//System.out.println(i + " --- " + unionFind.get(i));
group++;
}
}
return stones.length - group;
}
public static int findRoot(int i, HashMap<Integer, Integer> unionFind) {
while (unionFind.get(i) != i) {
i = unionFind.get(i);
}
return i;
}
}