N-Queens II 34

Question

Follow up for N-Queens problem.

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

Example

For n=4, there are 2 distinct solutions.

Solution

与N-Queens 33相同,不用具体记录每种解法,只要记录次数。

代码如下:

class Solution {
    /**
     * Calculate the total number of distinct N-Queen solutions.
     * @param n: The number of queens.
     * @return: The total number of distinct solutions.
     */
    int sum;
    public int totalNQueens(int n) {
        //write your code here
        sum = 0;
        int[] row = new int[n];
        NQueenHelper(row, 0);

        return sum;
    }

    private void NQueenHelper(int[] row, int rowNum){
        int n = row.length;

        if(rowNum == n){
            sum++;
            return;
        }

        for(int i = 0; i < n; i++){
            if(isValid(row, rowNum, i)){
                row[rowNum] = i;
                NQueenHelper(row, rowNum + 1);
                row[rowNum] = 0;
            }
        }
    }

    private boolean isValid(int[] row, int rowNum, int columnNum){
        for(int i = 0; i < rowNum; i++){
            if(row[i] == columnNum){
                return false;
            }

            if(Math.abs(row[i] - columnNum) == Math.abs(i - rowNum)){
                return false;
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""