947. 移除最多的同行或同列石头
n
块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。
如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。
给你一个长度为 n
的数组 stones
,其中 stones[i] = [xi, yi]
表示第 i
块石头的位置,返回 可以移除的石子 的最大数量。
示例 1:
输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
输出:5
解释:一种移除 5 块石头的方法如下所示:
1. 移除石头 [2,2] ,因为它和 [2,1] 同行。
2. 移除石头 [2,1] ,因为它和 [0,1] 同列。
3. 移除石头 [1,2] ,因为它和 [1,0] 同行。
4. 移除石头 [1,0] ,因为它和 [0,0] 同列。
5. 移除石头 [0,1] ,因为它和 [0,0] 同行。
石头 [0,0] 不能移除,因为它没有与另一块石头同行/列。
示例 2:
输入:stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]
输出:3
解释:一种移除 3 块石头的方法如下所示:
1. 移除石头 [2,2] ,因为它和 [2,0] 同行。
2. 移除石头 [2,0] ,因为它和 [0,0] 同列。
3. 移除石头 [0,2] ,因为它和 [0,0] 同行。
石头 [0,0] 和 [1,1] 不能移除,因为它们没有与另一块石头同行/列。
示例 3:
输入:stones = [[0,0]]
输出:0
解释:[0,0] 是平面上唯一一块石头,所以不可以移除它。
提示:
1 <= stones.length <= 1000
0 <= xi, yi <= 104
- 不会有两块石头放在同一个坐标点上
我的Java代码:
思路:可以把问题看做是连通图,每个坐标点都是一个点,同一行或者同一列的点都是相连的。要求可移除的最大数量,那么在一个连通分量中就要只保留一个点,这样问题就转化为求有几个连通分量。我是用并查集解决的,通过求根节点的个数判断有几个连通分量。
这里并查集的num和isConnected确实冗余了没有用到。。
class Solution {
public int removeStones(int[][] stones) {
if(stones == null || stones.length <= 1 || stones[0].length == 0) {
return 0;
}
int num = 0;
int len = stones.length;
UnionFind unionfind = new UnionFind(len);
for(int i = 0;i < len;i++) {
for(int j = i+1;j < len;j++) {
if(stones[i][0] == stones[j][0] || stones[i][1] == stones[j][1]) {
unionfind.union(i, j);
}
}
}
num = len - unionfind.getNum(len);
return num;
}
private class UnionFind{
private int parents[];
private int rank[];
private int num[];
public UnionFind(int n) {
parents = new int[n];
rank = new int[n];
num = new int[n];
for(int i = 0;i < n;i++) {
parents[i] = i;
rank[i] = 1;
num[i] = 1;
}
}
public void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if(rootX == rootY) {
return;
}
if(rank[rootX] > rank[rootY]) {
parents[rootY] = rootX;
num[rootX] += num[rootY];
}else if(rank[rootX] < rank[rootY]){
parents[rootX] = rootY;
num[rootY] += num[rootX];
}else {
parents[rootX] = rootY;
rank[rootY]++;
num[rootY] += num[rootX];
}
}
public int find(int x) {
if(parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
public boolean isConnected(int x, int y) {
int rootX = find(x);
int rootY = find(y);
return (rootX == rootY);
}
public int getNum(int n) {
int[] rootNum = new int[n];
int sum = 0;
for(int i = 0;i < n;i++) {
int root = find(i);
rootNum[root] = num[root];
}
for(int i = 0;i < n;i++) {
if(rootNum[i] != 0) {
sum++;
}
}
return sum;
}
}
}