題目
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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
解題之法
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > res;
vector<int> pos(n, -1);
solveNQueensDFS(pos, 0, res);
return res;
}
void solveNQueensDFS(vector<int> &pos, int row, vector<vector<string> > &res) {
int n = pos.size();
if (row == n) {
vector<string> out(n, string(n, '.'));
for (int i = 0; i < n; ++i) {
out[i][pos[i]] = 'Q';
}
res.push_back(out);
} else {
for (int col = 0; col < n; ++col) {
if (isValid(pos, row ,col)) {
pos[row] = col;
solveNQueensDFS(pos, row + 1, res);
pos[row] = -1;
}
}
}
}
bool isValid(vector<int> &pos, int row, int col) {
for (int i = 0; i < row; ++i) {
if (col == pos[i] || abs(row - i) == abs(col - pos[i])) {
return false;
}
}
return true;
}
};
分析
經(jīng)典的N皇后問題,基本所有的算法書中都會包含的問題,經(jīng)典解法為回溯遞歸,一層一層的向下掃描,需要用到一個pos數(shù)組,其中pos[i]表示第i行皇后的位置,初始化為-1,然后從第0開始遞歸,每一行都一次遍歷各列,判斷如果在該位置放置皇后會不會有沖突,以此類推,當?shù)阶詈笠恍械幕屎蠓藕煤?,一種解法就生成了,將其存入結(jié)果res中,然后再還會繼續(xù)完成搜索所有的情況,