1. 程式人生 > >LeetCode - Min Remaining Chess Pieces

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); } } } } }