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;
}
};