Oct 21, 2011

C Program to solve N Queen's problem

N Queen's problem is the puzzle. Placing chess queens on a chessboard, so thatNo two queens attack each other. Here we use the Brute-Force method to solve the problem.Read more about C Programming Language .


/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<stdio.h>
#include<conio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
 int i;
 for(i=1;i<pos;i++)
 {
  if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
   return 0;
 }
 return 1;
}
void print_sol(int n)
{
 int i,j;
 count++;
 printf("\n\nSolution #%d:\n",count);
 for(i=1;i<=n;i++)
 {
  for(j=1;j<=n;j++)
  {
   if(a[i]==j)
    printf("Q\t");
   else
    printf("*\t");
  }
  printf("\n");
 }
}
void queen(int n)
{
 int k=1;
 a[k]=0;
 while(k!=0)
 {
  a[k]=a[k]+1;
  while((a[k]<=n)&&!place(k))
   a[k]++;
  if(a[k]<=n)
  {
   if(k==n)
    print_sol(n);
   else
   {
    k++;
    a[k]=0;
   }
  }
  else
   k--;
 }
}
void main()
{
 int i,n;
 clrscr();
 printf("Enter the number of Queens\n");
 scanf("%d",&n);
 queen(n);
 printf("\nTotal solutions=%d",count);
 getch();
}
Read more Similar C Programs
Data Structures

Learn C Programming

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!