n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。
如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。
给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。
示例 1:
输入:stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]
输出:5
解释:一种移除 5 块石头的方法如下所示:
- 移除石头 [2,2] ,因为它和 [2,1] 同行。
- 移除石头 [2,1] ,因为它和 [0,1] 同列。
- 移除石头 [1,2] ,因为它和 [1,0] 同行。
- 移除石头 [1,0] ,因为它和 [0,0] 同列。
- 移除石头 [0,1] ,因为它和 [0,0] 同行。
石头 [0,0] 不能移除,因为它没有与另一块石头同行/列。
代码
class Solution {public int removeStones(int[][] stones) {int n=stones.length;List<List<Integer>> edge=new ArrayList<>();for(int i=0;i<n;i++){edge.add(new ArrayList<>());for(int j=0;j<n;j++){if(stones[i][0]==stones[j][0]||stones[i][1]==stones[j][1])
//有冲突的两个节点连成一条边edge.get(i).add(j);}}boolean[] check=new boolean[n];int res=0;for(int i=0;i<n;i++){if(!check[i]){res++;reStones(edge,check,i);}}return n-res;}public void reStones(List<List<Integer>> edge,boolean[] check,int cur) {//dfs将所有联通节点标记check[cur]=true;for(int c:edge.get(cur)){if (check[c]) continue;reStones(edge, check, c);}}
}