Question
Tips
Backtracking //You know ,I can do it well : )
Code
class Solution {
public:
Solution(){
res.clear();
rec=NULL;
}
~Solution(){
if(rec!=NULL)
delete []rec;
}
//Add one solution into result
void addResult(int n){
string stmp="";
vector<string> vtmp;
for(int row=0;row<n;++row){
for(int col=0;col<n;++col)
if(rec[row][col]==false)
stmp+=".";
else
stmp+="Q";
vtmp.push_back(stmp);
stmp="";
}
res.push_back(vtmp);
}
//Jugy
bool isOk(int x,int y,int n){
if(x%n==y%n) return false; //colume
if(x/n==y/n) return false; //row
if(abs(x%n-y%n)==abs(x/n-y/n)) return false;
return true;
}
void backTracking(int depth,int n){
if(depth==n){ //One result
addResult(n);
return;
}
bool flag=true; //Flag ,in order to jugy whether this Queen's position is legal
for(int i=0;i<n;++i){
rec[depth][i]=true;
flag=true;
for(int row=0;row<depth;++row){
for(int col=0;col<n;++col){
if(rec[row][col]==false)
continue;
if(isOk(row*n+col,depth*n+i,n)==false){
flag=false;
break;
}
}
if(flag==false)
break;
}
if(flag==false){
rec[depth][i]=false;
continue;
}else{
backTracking(depth+1,n);
rec[depth][i]=false;
}
}
}
vector<vector<string> > solveNQueens(int n) {
if(rec!=NULL)
delete []rec;
rec=new bool*[n];
for(int i=0;i<n;++i){
rec[i]=new bool[n];
memset(rec[i],false,n);
}
res.clear();
for(int i=0;i<n;++i){
rec[0][i]=true;
backTracking(1,n);
rec[0][i]=false;
}
return res;
}
private:
vector<vector<string> > res; //All the result
bool **rec; //Statement at now
};
Question
Tips
Always the backtracking.
This time , I think about the symmetry.
class Solution {
public:
Solution(){
rec=NULL;
totalNum=0;
}
~Solution(){
if(rec!=NULL)
delete []rec;
}
//Jugy
bool isOk(int x,int y,int n){
if(x%n==y%n) return false; //colume
if(x/n==y/n) return false; //row
if(abs(x%n-y%n)==abs(x/n-y/n)) return false;
return true;
}
void backTracking(int depth,int n){
if(depth==n){ //One result
++totalNum;
return;
}
bool flag=true; //Flag ,in order to jugy whether this Queen's position is legal
for(int i=0;i<n;++i){
rec[depth][i]=true;
flag=true;
for(int row=0;row<depth;++row){
for(int col=0;col<n;++col){
if(rec[row][col]==false)
continue;
if(isOk(row*n+col,depth*n+i,n)==false){
flag=false;
break;
}
}
if(flag==false)
break;
}
if(flag==false){
rec[depth][i]=false;
continue;
}else{
backTracking(depth+1,n);
rec[depth][i]=false;
}
}
}
int totalNQueens(int n) {
totalNum=0;
if(rec!=NULL)
delete []rec;
rec=new bool*[n];
for(int i=0;i<n;++i){
rec[i]=new bool[n];
memset(rec[i],false,n);
}
for(int i=0;i<n/2;++i){
rec[0][i]=true;
backTracking(1,n);
rec[0][i]=false;
}
if(n%2==0)
totalNum*=2;
else{
int tmp=totalNum;
rec[0][n/2]=true;
backTracking(1,n);
totalNum+=tmp;
}
return totalNum;
}
private:
int totalNum;
bool **rec; //Statement at now
};