Problem:
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Solution (C++):
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> ans(n, string(n, '.'));
solveNQueens(res, ans, 0, n);
return res;
}
private:
void solveNQueens(vector<vector<string>> &res, vector<string> &ans, int row, int n) {
if (row == n) {
res.push_back(ans);
return;
}
for (int col = 0; col < n; ++col) {
if (isValid(ans, row, col, n)) {
ans[row][col] = 'Q';
solveNQueens(res, ans, row+1, n);
ans[row][col] = '.';
}
}
}
bool isValid(vector<string> ans, int row, int col, int n) {
for (int i = 0; i < row; ++i) { //判断列是否有'Q'
if (ans[i][col] == 'Q') return false;
}
for (int i = row-1, j = col-1; i >= 0 && j >= 0; --i, --j) { //判断45°方向是否有'Q'
if (ans[i][j] == 'Q') return false;
}
for (int i = row-1, j = col+1; i >= 0 && j <= n-1; --i, ++j) { //判断135°方向是否有'Q'
if (ans[i][j] == 'Q') return false;
}
return true;
}