[路飞]leetcode-947.移除最多的同行或同列石头

82 阅读2分钟

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] 是平面上唯一一块石头,所以不可以移除它。

解题:

class UnionFind {
    constructor(length) {
      this.parent = new Array(length).fill(0).map((v, j) => j);
      this.rank = new Array(length).fill(1);
      this.setCount = length;
    }
    findSet(index) {
      if (this.parent[index] !== index) {
        this.parent[index] = this.findSet(this.parent[index]);
      }
      return this.parent[index];
    }
    unite(indei, index2) {
      let root1 = this.findSet(indei),
        root2 = this.findSet(index2);
      if (root1 !== root2) {
        if (this.rank[root1] < this.rank[root2]) {
          [root1, root2] = [root2, root1];
        }
        this.parent[root2] = root1;
        this.rank[root1] += this.rank[root2];
        this.setCount--;
      }
    }
    getCount() {
      return this.setCount;
    }
  }
var removeStones = function(stones) {
    const len=stones.length;
    const uf = new UnionFind(len)
    for (let i = 0; i < len; i++) {
        const [x1,y1] = stones[i];
        for (let j = i+1; j < len; j++) {
            const  [x2,y2]= stones[j];
            if(x1==x2||y1==y2){
                uf.unite(i,j)
            }            
        }
    }
    return len-uf.getCount()
};