和数独类似,用二进制记录状态去搜索,变量list记录当前列中存放情况,如果当前位为1 说明 当前数字存放了,否则反之,比如:
5代表0个和第2个数字存放了(从0开始)。
同理:变量left记录左斜线,变量right记录右斜线。
class Solution {
public:
int list,left,right;
int queen[111];
Solution(){list = 0,left = 0,right = 0;memset(queen,0,sizeof queen);}
vector<vector<string> >ans;
void change(int i,int j,int &n){
list^=(1<<j);
left^=(1<<(i+j));
right^=(1<<(i-j+n));
}
bool can(int i,int j,int &n){
bool a = 1;
a&= !(list & (1<<j));
a&= !(left & (1<<(i+j)));
a&= !(right & (1<<(i-j+n)));
return a;
}
void dfs(int k,int &n){
if(k==n){
std::vector<string> v;
for(int i = 0;i<n;++i){
string s(n,'.');
s[queen[i]] = 'Q';
v.push_back(s);
}
ans.push_back(v);
return;
}
for(int i = 0;i<n;++i){
if(can(k,i,n)){
change(k,i,n);
queen[k] = i;
dfs(k+1,n);
change(k,i,n);
}
}
}
vector<vector<string>> solveNQueens(int n) {
dfs(0,n);
return ans;
}
};