LeetCode #947 - Most Stones Removed with Same Row or Column

题目描述:

On a 2D plane, we place stones at some integer coordinate points.  Each coordinate point may have at most one stone.

Now, a move consists of removing a stone that shares a column or row with another stone on the grid.

What is the largest possible number of moves we can make?

 Example 1:

Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]

Output: 5

Example 2:

Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]

Output: 3

Example 3:

Input: stones = [[0,0]]

Output: 0

Note:

1. 1 <= stones.length <= 1000

2. 0 <= stones[i][j] < 10000

class Solution {
public:
    int removeStones(vector<vector<int>>& stones) {
        int n=stones.size();
        if(n<=1) return 0;
        for(int i=0;i<n;i++) parent[i]=i; //每个元素的初始化根节点都是自己
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<i;j++)
            {
                //发现横或纵坐标相同,将这两个元素的下标合并
                if(stones[i][0]==stones[j][0]||stones[i][1]==stones[j][1])
                    uni(i,j);
            }
        }
        
        int root_count=0;
        for(auto x: parent) if(x.first==x.second) root_count++;
        return n-root_count;
    }
    
    int find(int i)
    {
        if(parent[i]!=i) return find(parent[i]);
        else return i;
    }
    
    void uni(int i, int j)
    {
        int x=find(i);
        int y=find(j);
        parent[x]=y; //合并的操作就是将一个根的根节点设为另一个根
    }

private:
    unordered_map<int,int> parent;
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值