class Solution {
public:
vector<string> res;
vector<vector<string>> ans;
string temp;
bool isvalid(int n, int x, int y){
for(int i = x - 1; i >= 0; --i){
if(res[i][y] == 'Q') return false;
}
for(int i = x-1, j = y-1; i >=0 && j >=0; --i, --j){
if(res[i][j] == 'Q') return false;
}
for(int i = x-1, j = y+1; i >=0 && j < n; --i, ++j){
if(res[i][j] == 'Q') return false;
}
return true;
}
void backtracing(int n, int i){
if(i == n) {
ans.push_back(res);
return;
}
for(int j = 0; j < n; ++j){
if(isvalid(n, i, j)){
res[i][j] = 'Q';
backtracing(n, i+1);
res[i][j] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
res.assign(n, string(n, '.'));
backtracing(n, 0);
return ans;
}
};
Leecode51 N皇后
最新推荐文章于 2024-09-28 22:05:59 发布