I am trying to solve the famous NQUEENS problem using backtracking in c++ using vectors and class. But it is giving correct result for some cases(for ex. 5) and for remaining(for ex. 4) it is showing "Solutuon doesn't exist".
My code is as follows: Class declaration for storing rows and columns of queen position.
class position
{
public:
int r,c;
position(int r,int c)
{
this->r=r;
this->c=c;
}
};
The recursive function:
vector<position> positions;
bool solve(int n, int r)
{
if(r==n)
return true;
for (int c = 0; c < n; ++c)
{
bool safe=true;
for(int q=0;q<r;++q)
{
if (positions[q].c == c || positions[q].r - positions[q].c == r - c
|| positions[q].r + positions[q].c == r + c)
{
safe = false;
break;
}
}
if(safe)
{
position p(r,c);
positions.push_back(p);
if(solve(n,r+1))
return true;
}
}
return false;
}
and the driver function is as follows:
int main()
{
int n;
cin>>n;
if(!solve(n,0))
{
cout<<"Solution doesn't exist"<<endl;
return 0;
}
printboard(n);
return 0;
}
Please help me in resolving this.
if(solve(n,r+1))
return true;
else
positions.erase(positions.begin()+positions.size()-1);
If the solution for one cell doesn't exist then erase that cell from possible positions so that it avoids collisions. Edit:- Thank You Mr.Bo R for your correction.