LeetCode - Min Remaining Chess Pieces

探讨了在一个摆放有石子的棋盘上,如何通过深度优先搜索算法确定最多可以移除多少石子,以及为了达到最大移除数量应遵循的移除顺序策略。文章提供了一个Java实现的示例代码。

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

假设有一个棋盘(二维坐标系), 棋盘上摆放了一些石子(每个石子的坐标都为整数). 你可以remove一个石子, 当且仅当这个石子的同行或者同列还有其它石子. 输入是一个list of points.

问:
1) 给这些石子坐标, 你最多能remove多少个石子?
2) Follow-up: 若想保证remove的石子数量最大, 应按照什么顺序remove? (没有写代码)

 

DFS count connected components:

// "static void main" must be defined in a public class.
public class Main {
    public static void main(String[] args) {
        int[] a = {0,0};
        int[] b = {0,1};
        int[] c = {1,2};
        int[] d = {2,3};
        List<int[]> coords = new ArrayList<>();
        coords.add(a);
        coords.add(b);
        coords.add(c);
        coords.add(d);
        
        System.out.println(new Solution().minReminingChessPieces(coords));
    }
}
class Solution{
    
    public int minReminingChessPieces(List<int[]> coords){
        if(coords == null){
            return -1;
        }
        HashSet<String> visited = new HashSet<>();
        int res = 0;
        for(int[] coord : coords){
            String s = coord[0]+":"+coord[1];
            if(!visited.contains(s)){
                res++;
                DFSHelper(coords, coord, visited);
            }
        }
        return res;
    } 
    
    public void DFSHelper(List<int[]> coords, int[] coord, HashSet<String> visited){
        visited.add(coord[0]+":"+coord[1]);
        for(int[] subCoord : coords){
            if(subCoord[0] == coord[0] || subCoord[1] == coord[1]){
                if(!visited.contains(subCoord[0]+":"+subCoord[1])){
                    DFSHelper(coords, subCoord, visited);
                }
            }
        }
    }
    
}

 

转载于:https://www.cnblogs.com/incrediblechangshuo/p/10057411.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值