地址:https://leetcode-cn.com/problems/n-queens/
思路:DFS+剪枝
利用boo[x][y]判断(x,y)是否为皇后
在DFS搜索第k层时,若boo[k][i]为0,将其即为皇后,同时将其本身和其列与斜线b[][]+=1即可
Code:
class Solution {
vector<string> iv;
vector<vector<string>> res;
vector<vector<int>> boo;
public:
vector<vector<string>> solveNQueens(int n) {
if(!n) return {{}};
res.clear();
iv.assign(n,string(n,'.'));
boo.assign(n,vector<int>(n,0));
DFS(0,n);
return res;
}
void Sign(int n, int x, int y, int t){
int xi=x,yi=y;
while(xi<n){
boo[xi][y]+=t;
++xi;
}
xi=x; yi=y;
while(xi<n&&yi<n){
boo[xi][yi]+=t;
++xi; ++yi;
}
xi=x; yi=y;
while(xi<n&&yi>=0){
boo[xi][yi]+=t;
++xi; --yi;
}
}
void DFS(int k,int n){
if(k==n){
res.push_back(iv);
return;
}
for(int i=0;i<n;++i)
if(!boo[k][i]){
Sign(n,k,i,1);
iv[k][i]='Q';
DFS(k+1,n);
Sign(n,k,i,-1);
iv[k][i]='.';
}
}
};