【DFS】LeetCode 52. N 皇后 II

题目链接

52. N 皇后 II

思路

【DFS】LeetCode 51. N 皇后 一致

代码

class Solution {
    private int result;
    private boolean[] mainDiag;
    private boolean[] subDiag;
    private boolean[] column;

    public int totalNQueens(int n) {
        init(n);

        dfs(n, 0);

        return this.result;
    }

    private void dfs(int n, int row) {
        if(row == n){
            result++;
            return;
        }

        for(int col = 0; col < n; col++){
            if(column[col] || subDiag[row + col] || mainDiag[row - col + n - 1]){
                continue;
            }

            column[col] = true;
            subDiag[row + col] = true;
            mainDiag[row - col + n - 1] = true;

            dfs(n, row + 1);

            column[col] = false;
            subDiag[row + col] = false;
            mainDiag[row - col + n - 1] = false;
        }
    }

    private void init(int n) {
        this.result = 0;
        this.mainDiag = new boolean[2 * n - 1];
        this.subDiag = new boolean[2 * n - 1];
        this.column = new boolean[n];
    }
}
posted @ 2023-02-27 09:19  Frodo1124  阅读(17)  评论(0编辑  收藏  举报