N-Queens II

N-Queens II


Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

Please refer to the N-queens.

public class Solution {
    public int totalNQueens(int n) {
        List<Integer> ret = new ArrayList<Integer>();
        ret.add(0);
        
        helper(n,0,new int[n],ret);
        
        return ret.get(0);
    }
    
    private void helper(int n, int row, int[] columnForRow, List<Integer> ret) {
        if (n == row) {
            ret.set(0, ret.get(0)+1);
            return;
        } 
        for (int i = 0; i < n; i++) {
            columnForRow[row] = i;
            if (check(row, columnForRow)) {
                helper(n, row + 1, columnForRow, ret);
            }
        }
        
    }
    
    
    private boolean check(int row, int[] columnForRow) {
        for (int i = 0; i < row; i++) {
            if (columnForRow[i] == columnForRow[row] || Math.abs(columnForRow[i] - columnForRow[row]) == row - i)
                return false;
        }
        
        return true;
    }
}



 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章