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.
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.
Anaylse
就是一个N皇后问题,需要输出所有解决方案。在这里可以给不懂N皇后的问题小伙伴科普一下N皇后问题,N皇后问题原型为八皇后问题,问题要求在8 *8格的国际象棋棋盘上摆放八个皇后,使其不能互相攻击,即任意两个皇后不能处于同一行,同一列或同一斜线上(这个是国际象棋规则限制的)。N皇后问题即为在N *N的棋盘上摆放N个皇后,使其不能互相攻击。
这是一道十分典型的回溯问题,即枚举所有的摆放可能,然后判断是否可行。每次递归试放一个皇后,要是不符合规则,则取下来,再放到下一个位置。
Code
class Solution {
private:
// 用作斜线判断
bool judge(vector<string> board, int n, int x, int y) {
bool flag = true;
for (int i = 0; i < n; i++) {
if (board[i][y] == 'Q') {
flag = false;
break;
}
if ((x - i >= 0) && (y - i >= 0) && (board[x - i][y - i] == 'Q')) {
flag = false;
break;
}
if ((x - i >= 0) && (y + i < n) && (board[x - i][y + i] == 'Q')) {
flag = false;
break;
}
if ((x + i < n) && (y - i >= 0) && (board[x + i][y - i] == 'Q')) {
flag = false;
break;
}
if ((x + i < n) && (y + i < n) && (board[x + i][y + i] == 'Q')) {
flag = false;
break;
}
}
return flag;
}
void solve(vector<vector<string>>& ans, vector<string>& board, int n, int p) {
if (p == n) {
ans.push_back(board);
return;
}
for (int i = 0; i < n; i++) {
if (judge(board, n, p, i)) {
// 试放一个皇后
// 由于任意两个皇后不能放在同一行,所以可以直接每行放一个。
board[p][i] = 'Q';
solve(ans, board, n, p+1);
// 取回皇后
board[p][i] = '.';
}
}
return;
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> ans;
vector<string> board(n, string(n, '.'));
solve(ans, board, n, 0);
return ans;
}
};