Title Description
Given an integer n , returns all the different n solutions to the problem of the Queen. Each solution contains an explicit n queens problem pieces placed embodiment, the program 'Q'
and '.'
represent the space and queen.
输入: 4
输出: [
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
解释: 4 皇后问题存在两个不同的解法。
Problem-solving ideas
Backtracking algorithms classic title, must-see: backtracking algorithm explain . (Similar Title: full array)
Reference Code
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n, string(n, '.'));
backtrack(board, 0, n);
return res;
}
// 路径:board 中小于 row 的那些行都已经成功放置了皇后
void backtrack(vector<string> &board, int row, int n){
if(row == n){ // 触发结束条件
res.push_back(board);
return;
}
// 选择列表:第 row 行的所有列都是放置皇后的选择
for(int col = 0; col < n; col++){
// 排除不合法选择
if(!isValid(board, row, col, n))
continue;
board[row][col] = 'Q'; // 做选择
backtrack(board, row+1, n); // 进入下一行决策
board[row][col] = '.'; // 撤销选择
}
}
/* 是否可以在 board[row][col] 放置皇后? */
bool isValid(vector<string> &board, int row, int col, int n){
// 检查列是否有皇后互相冲突
for(int i = 0; i < n; i++){
if(board[i][col] == 'Q')
return false;
}
// 检查右上方是否有皇后互相冲突
for(int i = row-1, j = col+1; i >= 0 && j < n; i--, j++){
if(board[i][j] == 'Q')
return false;
}
// 检查左上方是否有皇后互相冲突
for(int i = row-1, j = col-1; i >= 0 && j >= 0; i--, j--){
if(board[i][j] == 'Q')
return false;
}
return true;
}
private:
vector<vector<string>> res;
};