Monday 14 March 2016

Lab program 12: Implement N Queen's problem using Back Tracking.

Description:
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other.
The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.

Algorithm
1.       Start in the leftmost column
2.        If all queens are placed
           return true
3.       Try all rows in the current column.  Do following for every tried row.
a)      If the queen can be placed safely in this row then mark this [row, column] as part of the solution and recursively check if placing queen here leads to a solution.
b)      If placing queen in [row, column] leads to a solution then return true.
c)      If placing queen doesn't lead to a solution then unmark this [row, column] (Backtrack) and go to step (a) to try other rows.
4.        If all rows have been tried and nothing worked, return false to trigger backtracking.

Solution:

#include<stdio.h>
int pos[10],count=0,n;

void display();

int place(int k)
{
  int i;
  for(i=1;i<k;i++)
   if((pos[i]==pos[k]) || (i-pos[i]==k-pos[k]) || (i+pos[i]==k+pos[k]))
     return 0;

  return 1;
}


void queen()
{
  int k=1;
  pos[k]=0;

  while(k!=0)
  {
    pos[k]=pos[k]+1;

    while(pos[k]<=n && !place(k))
       pos[k]=pos[k]+1;

    if(pos[k]<=n)

       if(k==n)
       {
            count++;
            printf("\n\n Solution:%d\n\n",count);
            display();
       }

       else
       {
        k=k+1;
        pos[k]=0;
       }

    else
       k=k-1;
  }
}

void display()
{
   int i,j;
   for(i=1;i<=n;i++)
   {

    for(j=1;j<=n;j++)
      if(j==pos[i])
            printf(" Q ");
      else
            printf(" _ ");
      printf("\n\n");
   }
}
void main()                                                                   
{
printf("Enter the no of queens:\n");
scanf("%d",&n);
queen();
printf("\n\nTotal no of solutions=%d\n",count);
}



OUTPUT :

Enter the no of queens
4
Solution 1:
_       Q       _       _
_       _       _       Q
Q       _       _       _
_       _       Q       _

Solution 2:
_       _       Q       _
Q       _       _       _
_       _       _       Q
_       Q       _       _


Total no of solutions=2

No comments:

Post a Comment