首页 > 其他分享 >【DFS】LeetCode 52. N 皇后 II

【DFS】LeetCode 52. N 皇后 II

时间:2023-02-27 09:23:00浏览次数:54  
标签:int DFS col II boolean private mainDiag LeetCode row

题目链接

52. N 皇后 II

思路

52. N 皇后 II 一致

代码

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

标签:int,DFS,col,II,boolean,private,mainDiag,LeetCode,row
From: https://www.cnblogs.com/shixuanliu/p/17158544.html

相关文章