Problem
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 <= stonesi < 10000
Solution
class Solution {
public int removeStones(int[][] stones) {
int m = stones.length;
int[] parents = new int[m];
for (int i = 0; i < m; i++) {
parents[i] = i;
}
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = i+1; j < m; j++) {
if (stones[j][0] == stones[i][0] || stones[j][1] == stones[i][1]) {
int p1 = find(parents, i);
int p2 = find(parents, j);
parents[p1] = p2;
if (p1 != p2) {
count++;
}
}
}
}
return count;
}
private int find(int[] parents, int i) {
if (parents[i] == i) return i;
else return find(parents, parents[i]);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。