N皇后问题
- 问题描述:leetcode:51
- [
https://leetcode.com/problems/n-queens/
][1]
思路:
- 利用回溯法。
- 一行一行往下遍历,在每行中又看每一列中的位置是否与之前的放Q的位置形成冲突。
- 冲突又四种:同行、同列、正斜线、反斜线。
- 同行不需要考察,因为当一行中放了一个Q时,进行下一行的遍历了。
- 在进行下一行遍历的函数后面,把放置的Q的那个位置还要重新放“.”;因为还要考察本行后面的位置是否还可以形成答案。
按照思路写的代码:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > res;
vector<string> nQueens(n, string(n, '.'));
solveNQueens(res, nQueens, 0, n);
return res;
}
void solveNQueens(vector<vector<string> > &res, vector<string> &nQueens, int row, int &n) {
if (row == n) {
res.push_back(nQueens);
return;
}
for (int col = 0; col != n; ++col)
if (isValid(nQueens, row, col, n)) {
nQueens[row][col] = 'Q';
solveNQueens(res, nQueens, row + 1, n);
nQueens[row][col] = '.';
}
}
bool isValid(vector<string> &nQueens, int row, int col, int &n) {
for (int i = 0; i != row; ++i)
if (nQueens[i][col] == 'Q')
return false;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j)
if (nQueens[i][j] == 'Q')
return false;
for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j)
if (nQueens[i][j] == 'Q')
return false;
return true;
}