51. N皇后( 深度优先遍历)
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。
每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。
解题思路: 本题参考了Grandyang的博客,采用DFS去枚举所有的可能。
注:皇后不会攻击条件,同一行同一列或者两条对角线上都没有其他皇后,则不会攻击。
class Solution {
public:
void dfs(int curRow, int n, vector<string> &out, vector<vector<string>> &res) {
if (curRow >= n) {
res.push_back(out);
return;
}
for (int i = 0; i < n; ++i) {
if (isValid(out, n, curRow, i)) {
out[curRow][i] = 'Q';
dfs(curRow + 1, n, out, res);
out[curRow][i] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> out(n, string(n, '.'));
vector<vector<string>> res;
dfs(0, n, out, res);
return res;
}
bool isValid(vector<string> &out, int n, int curRow, int curCol) {
for (int i = curRow - 1; i >= 0; --i) {
if (out[i][curCol] == 'Q') return false;
}
for (int i = curRow - 1, j = curCol - 1; i >=0 && j >= 0; --i, --j) {
if (out[i][j] == 'Q') return false;
}
for (int i = curRow - 1, j = curCol + 1; i >= 0 && j < n; --i, ++j) {
if (out[i][j] == 'Q') return false;
}
return true;
}
};