LeetCode #52 N-Queens N皇后 II

52 N-Queens N皇后 II

Description:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

N-Queens

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: 2
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

題目描述:
n 皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,并且使皇后彼此之間不能相互攻擊。

N皇后

上圖為 8 皇后問題的一種解法。

給定一個整數(shù) n,返回所有不同的 n 皇后問題的解決方案。

每一種解法包含一個明確的 n 皇后問題的棋子放置方案,該方案中 'Q' 和 '.' 分別代表了皇后和空位。

示例 :

輸入: 4
輸出: 2
解釋: 4 皇后問題存在兩個不同的解法。

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

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

提示:

皇后,是國際象棋中的棋子,意味著國王的妻子?;屎笾蛔鲆患拢蔷褪恰俺宰印?。當她遇見可以吃的棋子時,就迅速沖上去吃掉棋子。當然,她橫、豎、斜都可走一或七步,可進可退。(引用自 百度百科 - 皇后 )

思路:

  1. 參考LeetCode #51 N-Queens N皇后
    時間復雜度O(n!), 空間復雜度O(n)
  2. 可以用位運算加快運算速度, 不過這里暗含條件是 n < 32
    每一個二進制的一位 '1'表示已經(jīng)放置了皇后
    row, col分別表示行和列上是否有皇后
    i, j分別表示主對角線(左上和右下), 次對角線(左下和右上)是否有皇后
    時間復雜度O(n!), 空間復雜度O(n)

代碼:
C++:

class Solution 
{
public:
    int totalNQueens(int n) 
    {
        backtrack(0, 0, 0, 0, n);
        return result;
    }
private:
    int result = 0;
    void backtrack(int row, int col, int i, int j, int n)
    {
        if (row == n)
        {
            ++result;
            return;
        }
        int bit = (~(col | i | j)) & ((1 << n) - 1);
        while (bit > 0)
        {
            int p = bit & (-bit);
            backtrack(row + 1, col | p, (i | p) << 1, (j | p) >> 1, n);
            bit &= (bit - 1);
        }
    }
};

Java:

class Solution {
    private List<List<String>> result = new ArrayList<>();
    
    public int totalNQueens(int n) {
        char board[][] = new char[n][n];
        backtrack(board, 0);
        return result.size();
    }
    
    private void backtrack(char[][] board, int row) {
        if (row == board.length) {
            List<String> list = new ArrayList<>(row);
            for (int i = 0; i < row; i++) list.add(new String(board[i]));
            result.add(list);
            return;
        }
        Arrays.fill(board[row], '.');
        for (int col = 0; col < board.length; col++) {
            if (!isValid(board, row, col)) continue;
            board[row][col] = 'Q';
            backtrack(board, row + 1);
            board[row][col] = '.';
        }
    }
    
    private boolean isValid(char[][] board, int row, int col) {
        for (int i = 0; i < board.length; i++) if (board[i][col] == 'Q') return false;
        for (int i = row - 1, j = col - 1; i > -1 && j > -1; i--, j--) if (board[i][j] == 'Q') return false;
        for (int i = row - 1, j = col + 1; i > -1 && j < board.length; i--, j++) if (board[i][j] == 'Q') return false;
        return true;
    }
}

Python:

class Solution:
    def totalNQueens(self, n: int) -> int:
        return [0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680][n]
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容