Search code examples
c++cbacktracking

How to proceed further in this 8 queen algorithm?


The code and output is working fine before backtracking but I am not able to proceed for backtracking. What to do do after unplacing? It is giving the output of first 4 queens only means before backtracking.

    #include <iostream>
    #include <conio.h>
    using namespace std;
    int recu(int i,int k);
    void place(int i,int k);
    void unplace(int i,int k);
    int q[8][8];
    int row[8];
    int column[8];
    int c[15];
    int d[15];
    int totalqueens=0;
    int s;

    int main()
    {
        for(int i=0;i<8;i++) //Flags for rows,columns and diagonals
        {
        row[i]=0;
        column[i]=0;
        c[i]=0;d[i]=0;
        }
        for(int i=8;i<15;i++)
        {
        c[i]=0;d[i]=0;
        }
        int i=0;
        int k=0;
        recu(i,k);


      for(int i=0;i<8;i++)
      {
          for(int k=0;k<8;k++)
          {
                if(q[i][k]==1)
                {
                   cout<<"(";
                   cout<<i;
                   cout<<",";
                   cout<<k;
                   cout<<")";
                }
           }
     }

    getch();
    return 0;
}

int recu(int i,int k)
{ 
     if(totalqueens==8)
     {  goto print; }
     if(k<8)
      {
          if(column[i]==0 && row[k]==0 && c[i+k]==0 && d[i-k+7]==0)
           {
             place(i,k);

             s=k;
             k=0;
             recu(i+1,k);
           }
           else
           { 
             recu(i,k+1);
             unplace(i-1,s);
            //**I am not able to proceed further**
           }

      }

print:
    ;
}

void place(int i,int k)
{     
    totalqueens++;
    q[i][k]=1;
    row[k]=1;
    column[i]=1;
    c[i+k]=1;
    d[i-k+7]=1;
}

void unplace(int i,int k)
{
    q[i][k]=0;
    row[i]=0;
    column[k]=0;
    c[i+k]=0;
    d[i-k+7]=0;
    //cout<<"before call";
    recu(i,k+1);
    //cout<<"working";
}

Solution

  • Your code only gives out one solution. u r not put the output part in the right place.

    try like this:

    void print()
    {
          for(int i=0;i<8;i++)
          {
              for(int k=0;k<8;k++)
              {
                    if(q[i][k]==1)
                    {
                       cout<<"(";
                       cout<<i;
                       cout<<",";
                       cout<<k;
                       cout<<")";
                    }
               }
         }
    }
    

    make that to be one method. and then, in your recu method, modify to:

    if(totalqueens==8)
    {
        print();
        return;
    }
    

    Keep in mind that DO NOT use goto sentence. It is very ugly and may cause unknown problems.