I have written a program for the 8-Queens problem.It prints all possible solutions.

queens() finds all the possible solutions. ok() tells whether the given column and row is safe or not.

The very strange problem is:

'Count' won't increment. I have no idea why.

  #include<iostream.h>
    #include<stdlib.h>
    #include<conio.h>

    int arr[8][8]={0};
    int count=0;

    int ok(int k,int j)
    {
     int i,l;
     int tup[8]={0};

     for(i=0;i<k;i++)
     {
      for(l=0;l<8;l++)
      {
       if(arr[i][l]==1)
       tup[i]=l;
      }
     }

     for(i=0;i<k;i++)
     {
      if((abs(tup[i]-j)==abs(i-k))||(tup[i]==j)||(arr[i][j]==1))
      return 0;
     }

     return 1;

    }


    void queen(int i)
    {
     int j,k,temp;

     if(i==8)
     {
      count++;
      cout<<"Solution no. "<<count<<":\n";

      for(i=0;i<8;i++)
      {
       for(j=0;j<8;j++)
       {
        if(arr[i][j]==1)
        cout<<char(81);
        else
        cout<<"=";
        cout<<" ";
       }
       cout<<"\n";
      }
      cout<<"---------------\n";

      getch();

     }

     for(j=0;j<8;j++)
     {
      if(ok(i,j))
      {
       for(k=0;k<8;k++)
       arr[i][k]=0;
       arr[i][j]=1;
       queen(i+1);
      }
     }

     arr[i][j]=0;

    }



    int main()
    {
     int i,j;

     clrscr();

     queen(0);

     return 0;

    }

I'll give you a hint: check your array indices where the element is being set to 0. You're overrunning one of your arrays and count happens to be at that address.

commented: thanks. it works with a return; added in if(i==8) +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.