Wednesday, January 8, 2014

The N-Queens problem, A simple approach

Welcome back Guys...Got time to write my next topic...Hope everyone is doing great!!! ;) ;)

Let's Start with the problem :-
The N-queens problem consists in placing N non-attacking queens on an N-by-N chess board. A queen can attack another queen vertically, horizontally, or diagonally. E.g. placing a queen on a central square of the board blocks the row and column where it is placed, as well as the two diagonals (rising and falling) at whose intersection the queen was placed.



"This is typically looking a very complex questions for budding coders but I bet it is not so, Let's tackle it as below, It has 92 distinct and 12 unique (after removing rotations and reflections) solutions...and it's my own work, not to mention ;) ;) ) ".

Idea:- The algorithm to solve this problem uses backtracking.Let we have N*N square where we have to place N queens,you must be thinking to create an square of size N*N... oh No Not at all!!!. Create an array (single dimensional), and try to put every possible column  number to put so we have to check every time is there any Queen crossing this position if not go for next rows otherwise get back to previous row and try is there any other possible solution for this row...repeat until you don't get your solution hence back and forth.

To check attacking queens we can try this way: let assume r1 and c1 are already placed queens positions respectively , r2  and c2 are to be placed queens, they will attack each other
if  r1==r2 OR c1==c2 OR absolute(r1-r2)==absolute(c1-c2)

Here the complete Running code:
/*Author Atiqur Rahman on blog atiqwhiz.blogspot.in*/
#include <iostream>

#define N 8
using namespace std;
bool nQueens(int solve[],int n)
{
 int j,r1,r2,c1,c2;
  if(n==N)
  return true;
  for(int i=0;i<N;i++)
  {
      r2=n;
      c2=i;
      for(j=0;j<n;j++)
      {   r1=j;
          c1=solve[j];
        if(r1==r2||c1==c2||abs(r1-r2)==abs(c1-c2))
         break;
      }
    if(j==n)
    {
        solve[n]=i;
        if(nQueens(solve,n+1))
         return true;
    }
  }

return false;
}

int main()
{
   int solve[N];
   if(nQueens(solve,0))
   {   cout<<"Row     Column\n";
       for(int j=0;j<N;j++)
       {
           cout<<j<<"          "<<solve[j]<<endl;
       }
   }
   else
   {
       cout<<"\n\nNo such combination is possible";
   }
 
   return 0;
}


//Happy Coding...
//Let me know if anything is not working....will be happy to respond.


No comments:

Post a Comment