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

【DFS】LeetCode 51. N 皇后

时间:2023-02-27 08:44:17浏览次数:48  
标签:int mainDiagonal 51 DFS boolean private new LeetCode row

题目链接

51. N 皇后

思路

代码

class Solution {
    private List<List<String>> result;
    private boolean[] mainDiagonal;
    private boolean[] subDiagonal;
    private boolean[] column;
    private int[] board;

    public List<List<String>> solveNQueens(int n) {
        init(n);
        dfs(n, 0);

        return result;
    }

    private void dfs(int n, int row) {
        if(row == n){
            List<String> temp = new ArrayList<>();
            for(int i : board){
                char[] str = new char[n];
                Arrays.fill(str, '.');
                str[i] = 'Q';
                temp.add(new String(str));
            }
            result.add(temp);

            return;
        }

        for(int i = 0; i < n; i++){
            if(column[i] || mainDiagonal[row + i] || subDiagonal[row - i + n - 1]){
                continue;
            }
            board[row] = i;
            column[i] = true;
            mainDiagonal[row + i] = true;
            subDiagonal[row - i + n - 1] = true;

            dfs(n, row + 1);

            column[i] = false;
            mainDiagonal[row + i] = false;
            subDiagonal[row - i + n - 1] = false;
        }
    }

    private void init(int n) {
        this.column = new boolean[n];
        this.mainDiagonal = new boolean[2 * n - 1];
        this.subDiagonal = new boolean[2 * n - 1];
        this.board = new int[n];
        this.result = new ArrayList<>();
    }
}

标签:int,mainDiagonal,51,DFS,boolean,private,new,LeetCode,row
From: https://www.cnblogs.com/shixuanliu/p/17158449.html

相关文章