/*深度搜索。*/
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 发布