1. 程式人生 > 其它 >力扣打卡2021.1.15 移除最多的同行或同列石頭

力扣打卡2021.1.15 移除最多的同行或同列石頭

技術標籤:力扣打卡leetcode

題目:
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 塊石頭的方法如下所示:
  6. 移除石頭 [2,2] ,因為它和 [2,0] 同行。
  7. 移除石頭 [2,0] ,因為它和 [0,0] 同列。
  8. 移除石頭 [0,2] ,因為它和 [0,0] 同行。
    石頭 [0,0] 和 [1,1] 不能移除,因為它們沒有與另一塊石頭同行/列。
    示例 3:
    輸入:stones = [[0,0]]
    輸出:0
    解釋:[0,0] 是平面上唯一一塊石頭,所以不可以移除它。
    程式碼(並查集)
class DisjointSetUnion {
private:
    unordered_map<int, int> f, rank;

public:
    int find(int x) {
        if (!f.count(x)) {
            f[x] = x;
            rank[x] = 1;
        }
        return f[x] == x ? x : f[x] = find(f[x]);
    }

    void unionSet
(int x, int y) { int fx = find(x), fy = find(y); if (fx == fy) { return; } if (rank[fx] < rank[fy]) { swap(fx, fy); } rank[fx] += rank[fy]; f[fy] = fx; } int numberOfConnectedComponent() { int num = 0; for (auto &[x, fa] : f) { if (x == fa) { num++; } } return num; } }; class Solution { public: int removeStones(vector<vector<int>> &stones) { int n = stones.size(); DisjointSetUnion dsu; for (int i = 0; i < n; i++) { dsu.unionSet(stones[i][0], stones[i][1] + 10000); } return n - dsu.numberOfConnectedComponent(); } };