by the way for 45 & 135 degree ,there are two equations:
- y-c = 1*(x-r) ⇒ x+y == r+c
- y-c = -1*(x-r) ⇒ x-y == r-c
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> q(n,string(n,'.'));
solve(res,q,0,n);
return res;
}
void solve(vector<vector<string>>& res,vector<string>& q,int r,int n){
if(r==n){
res.push_back(q);
return ;
}
for(int j=0;j<n;j++){
if(isValid(q,r,j,n)){
q[r][j] = 'Q';
solve(res,q,r+1,n);
q[r][j] = '.';
}
}
}
bool isValid(vector<string>& q,int r,int c,int n){
//row&col
for(int i=0;i<n;i++){
if(q[r][i]=='Q'||q[i][c]=='Q'){
return false;
}
}
//45 degree & 135 degree
for(int x=0;x<n;x++){
for(int y=0;y<n;y++){
if(x-y==r-c||x+y==r+c){
if(q[x][y]=='Q'){
return false;
}
}
}
}
return true;
}
};
Solution B: Use flag vectors as bitmask, 4ms:
The number of columns is n, the number of 45° diagonals is 2 * n - 1, the number of 135° diagonals is also 2 * n - 1. When reach [row, col], the column No. is col, the 45° diagonal No. is row + col and the 135° diagonal No. is n - 1 + col - row. We can use three arrays to indicate if the column or the diagonal had a queen before, if not, we can put a queen in this position and continue.
NOTE: Please don’t use vector flag to replace vector flag in the following C++ code. In fact, vector is not a STL container. You should avoid to use it. You can also get the knowledge from here and here.
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<string> q(n,string(n,'.'));
vector<int> flag_col(n,1),flag_45(2*n-1,1),flag_135(2*n-1,1);
solve(res,q,0,n,flag_col,flag_45,flag_135);
return res;
}
void solve(vector<vector<string>>& res,vector<string>& q,int r,int n,vector<int>& flag_col,vector<int>& flag_45,vector<int>& flag_135){
if(r==n){
res.push_back(q);
return ;
}
for(int j=0;j<n;j++){
if(flag_col[j]&&flag_45[r+j]&&flag_135[n-1+j-r]){
flag_col[j]=flag_45[r+j]=flag_135[n-1+j-r]=0;
q[r][j] = 'Q';
solve(res,q,r+1,n,flag_col,flag_45,flag_135);
q[r][j] = '.';
flag_col[j]=flag_45[r+j]=flag_135[n-1+j-r]=1;
}
}
}
};