【LeetCode】51. N-Queens 解題報告(C++)
阿新 • • 發佈:2018-12-30
作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/
目錄
題目地址:https://leetcode.com/problems/n-queens/
題目描述
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
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: [ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
題目大意
求n皇后問題的每個解。注意題意,n皇后問題是在n*n的棋盤上放n個皇后,每一種放置方案。
解題方法
回溯法
這個題是52. N-Queens II題目的拓展,52題只要求了統計個數,這個題要求把每一種結果寫出來。其實程式碼基本一樣了,只是最後在搜尋到對應的解的時候,52題只把結果+1即可,現在的這個題需要構造出對應的放置方案,然後放入到res中。
所以定義了兩個函式:helper函式是我們即將要處理row行了,進行回溯;isValid是我們如果這一步放在第row,col位置,合不合法?
python程式碼如下:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> board(n, -1);
vector<vector<string>> res;
helper(board, res, 0);
return res;
}
// how to put in row? (havent put down yet)
void helper(vector<int>& board, vector<vector<string>>& res, int row) {
const int N = board.size();
if (row == N) {
vector<string> path(N, string(N, '.'));
for (int i = 0; i < N; i++) {
path[i][board[i]] = 'Q';
}
res.push_back(path);
} else {
for (int col = 0; col < N; col++) {
board[row] = col;
if (isValid(board, row, col)) {
helper(board, res, row + 1);
}
board[row] = -1;
}
}
}
// have put down in (row, col), alright?
bool isValid(vector<int>& board, int row, int col) {
for (int prow = 0; prow < row; prow ++) {
int pcol = board[prow];
if (pcol == col || abs(prow - row) == abs(pcol - col)) {
return false;
}
}
return true;
}
};
日期
2018 年 12 月 23 日 —— 周賽成績新高