LeetCode - Min Remaining Chess Pieces

假设有一个棋盘(二维坐标系), 棋盘上摆放了一些石子(每个石子的坐标都为整数). 你可以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);
                }
            }
        }
    }
    
}

猜你喜欢

转载自www.cnblogs.com/incrediblechangshuo/p/10057411.html