51. N-Queens
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;
}
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。