/*深度搜索。*/
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > res;
if(n < 1) return res;
vector<int> path;
vector<vector<int> > res_num;
dfs(res_num, path, n, 0);
for(int i = 0; i < res_num.size(); ++i){
vector<string> tmp_res;
for(int j = 0; j < res_num[i].size(); ++j){
string s(n, '.');
s[res_num[i][j]] = 'Q';
tmp_res.push_back(s);
}
res.push_back(tmp_res);
}
return res;
}
void dfs(vector<vector<int> > &res, vector<int> &path, int n, int cur){
if(cur == n){
res.push_back(path);
return;
}
else{
for(int i = 0; i < n; ++i){
bool i_can = true;
for(int j = 0; j < path.size(); ++j){
if(i == path[j] || (abs(i-path[j]) == abs(cur - j))){
i_can = false;
break;
};
}
if(i_can){
path.push_back(i);
dfs(res, path, n, cur+1);
path.pop_back();
}
}
}
}
};LeetCode之N-Queens
最新推荐文章于 2022-06-06 22:03:40 发布
本文介绍了一种使用深度优先搜索(DFS)解决N皇后问题的方法。通过递归地尝试将皇后放置在棋盘的不同位置上,并检查每一步是否违反了N皇后问题的规则,最终找到所有可行的解决方案。
598

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



