程序员面试金典-面试题 08.12. 八皇后

题目:

设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。

注意:本题相对原题做了扩展

示例:

输入:4
输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
解释: 4 皇后问题存在如下两个不同的解法。
[
 [".Q..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
]

分析:

经典老题了,就不多说了,下面有一篇已经写好的讲解,不懂的同学可以移步下面看看。

LeetCode 51. N-QueensN皇后 (C++)(八皇后问题)

程序:

class Solution {
    public List<List<String>> solveNQueens(int n) {
        cols = new int[n];
        leftDiagonal = new int[n * 2 - 1];
        rightDiagonal = new int[n * 2 - 1];
        List<List<String>> res = new ArrayList<>();
        char[][] chess = new char[n][n];
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < n; ++j)
                chess[i][j] = '.';
        dfs(chess, res, 0, n);
        return res;
    }
    private void dfs(char[][] chess, List<List<String>> res, int x, int n){
        if(x == n){
            List<String> list = new ArrayList<>();
            for(char[] c:chess){
                list.add(new String(c));
            }
            res.add(list);
            return;
        }
        for(int y = 0; y < n; ++y){
            if(cols[y] == 1 || leftDiagonal[-x+y+n-1] == 1 || rightDiagonal[-x-y+(n-1)*2] == 1)
                continue;
            cols[y] = 1;
            leftDiagonal[-x+y+n-1] = 1;
            rightDiagonal[-x-y+(n-1)*2] = 1;
            chess[x][y] = 'Q';
            dfs(chess, res, x+1, n);
            cols[y] = 0;
            leftDiagonal[-x+y+n-1] = 0;
            rightDiagonal[-x-y+(n-1)*2] = 0;
            chess[x][y] = '.';
        }
        return;
    }
    private int[] cols;
    //-x+y+n-1
    private int[] leftDiagonal;
    //-x-y+(n-1)*2
    private int[] rightDiagonal;
}

猜你喜欢

转载自www.cnblogs.com/silentteller/p/12469024.html