leetcode -- 947. Most Stones Removed with Same Row or Column

本文探讨了一种在二维平面上消除最多石子的策略。通过分析石子在横纵坐标上的分布,利用深度优先搜索(DFS)算法寻找连通分量,从而计算出可以消除的最大石子数量。文章提供了详细的算法实现和示例解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 <= stones.length <= 1000
0 <= stones[i][j] < 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-stones-removed-with-same-row-or-column
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

思路:

1、半天读不懂题意系列,可以移动横坐标或纵坐标相同的石头。也就是当他们横坐标或纵坐标相同时,是连通的。连通的就可以一个一个接着取掉。

2、所以dfs思路就是:找到连通分量,用石子数量-连通分量就是可以remove的个数

 

class Solution {
public:
    int removeStones(vector<vector<int>>& stones) {
        vector<bool> vis(stones.size(), false);
        int count = 0;
        for(int i = 0; i < stones.size(); i++){
            if(!vis[i]){
                dfs(i,{stones[i][0], stones[i][1]}, vis, stones);
                count++;
            }
        }
        return stones.size() - count;
    }
    
    void dfs(int idx, pair<int, int> p, vector<bool>& vis, vector<vector<int>>& stones){
        vis[idx] = true;
        for(int i = 0; i < stones.size(); i++){
            int x = stones[i][0], y = stones[i][1];
            if((p.first == x || p.second == y)&&!vis[i]){
                vis[i] = true;
                dfs(i,{x,y},vis,stones);
            }
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值