java 52. N-Queens II.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 52. N-Queens II.java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int totalNQueens(int n) {
        int[] res = {0}; // basic type will be passed by value
        boolean[] positions = new boolean[n]; // columns   |
        boolean[] d1 = new boolean[2 * n];// diagonals \
        boolean[] d2 = new boolean[2 * n];// diagonals /
        backtracking(res, 0, positions, d1, d2, n);
        return res[0];
        
    }
    
    private void backtracking(int[] res, int row, boolean[] positions, boolean[] d1, boolean[] d2, int n) {
        if(row == n) res[0]++;
        
        for(int curCol = 0; curCol < n; curCol++) {
            int diff = curCol - row + n;
            int sum = curCol + row;
            
            if(positions[curCol] || d1[diff] || d2[sum]) continue;
            
            positions[curCol] = true;
            d1[diff] = true;
            d2[sum] = true;
            backtracking(res, row + 1, positions, d1, d2, n);
            positions[curCol] = false;
            d1[diff] = false;
            d2[sum] = false;
        
        }
    }
}

以上是关于java 52. N-Queens II.java的主要内容,如果未能解决你的问题,请参考以下文章

java 52. N-Queens II.java

java 52. N-Queens II.java

java 52. N-Queens II.java

java 52. N-Queens II.java

52. N-Queens II

一天一道LeetCode#52. N-Queens II