【题解】 移除最多的同行或同列石头

n 块石头放置在二维平面中的一些整数坐标点上。每个坐标点上最多只能有一块石头。

如果一块石头的 同行或者同列 上有其他石头存在,那么就可以移除这块石头。

给你一个长度为 n 的数组 stones ,其中 stones[i] = [xi, yi] 表示第 i 块石头的位置,返回 可以移除的石子 的最大数量。

同行同列的石头放入一个集合,像是岛屿数量的升级版,但这个使用洪水填充就没法做。

class Solution {
public:
    int fa[1001];
    int sets;
    int find(int x) {
        if(fa[x] != x) {
            fa[x] = find(fa[x]);
        }
        return fa[x];
    }
    void merge(int x,int y) {
        int fx = find(x),fy = find(y);
        if(fx != fy) {
            fa[fx] = fy;
            sets--;
        }
    }
    int removeStones(vector<vector<int>>& stones) {
        int n = stones.size();
        map<int,int> row,col;
        sets = n;
        for(int i = 0; i < n; i++) fa[i] = i;
        for(int i = 0; i < n; i++) {
            int r = stones[i][0],c = stones[i][1];
            if(col.find(c) == col.end()) {
                col[c] = i;
            } else {
                merge(col[c],i);
            }
            cout<<sets<<endl;
            if(row.find(r) == row.end()) {
                row[r] = i;
            } else {
                merge(row[r],i);
            }
        }
        return n-sets;
    }
};
github