class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
N = n;
vector<string> col(n, string(n, '.'));
dfs(-1, col);
return _ret;
}
void dfs(int i, vector<string>& col)
{
if (i == N - 1)
{
#ifdef PRINT
cout << ++cnt << "===\n";
for (auto v : col)
{
cout << v << "\n";
}
cout << "\n";
#endif
_ret.push_back(col);
}
else
{
for (size_t j = 0; j < N; j++)
{
col[i + 1] = string(N, '.');
col[i+1][j] = 'Q';
if(isPromise(i+1, j, col))
dfs(i + 1, col);
}
}
}
bool isPromise(int i, int j, vector<string>& col)
{
for (int k = 0; k < i; k++)
{
if (col[k][j] == col[i][j])
{
return false;
}
int d = abs(i - k);
if ( (j -d >= 0 && col[i][j] == col[k][ abs( j-d )])
|| (j + d < col.size() && col[i][j] == col[k][j + d]) )
{
return false;
}
}
return true;
}
int N;
int cnt = 0;
vector<vector<string>> _ret;
};
leetcode51. N皇后
最新推荐文章于 2024-04-12 17:02:43 发布
本文介绍了一种使用深度优先搜索(DFS)解决N皇后问题的方法,通过递归地放置皇后并检查每一步是否冲突,最终找到所有可能的解决方案。代码详细展示了如何判断皇后之间的冲突,以及如何在棋盘上放置和移除皇后。
386

被折叠的 条评论
为什么被折叠?



