简体   繁体   中英

C++ recursive solution of NQUEENS problem not working properly

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM