N Queen Problem using c and c++

N Queen Problem using c and c++

Here you will get a program for N queens problem in C using backtracking.
N Queens Problem is a famous puzzle in which n-queens are to be placed on a nxn chessboard such that no two queens are in the same row, column or diagonal. In this tutorial, I am sharing the C program to find a solution for N Queens problem using backtracking. Below animation shows the solution for 8 queens problem using backtracking.


#include<stdio.h>
#include<conio.h>
#include<math.h>

int x[100];

void main()
{
                clrscr();

                void n_queen(int,int);
                int n;

                printf("\n\t Enter Queen Value : ");
                scanf("%d",&n);

                n_queen(1,n);
                getch();
}

void n_queen(int k,int n)
{
                int p(int ,int);
                for(int i=1;i<=n;i++)
                {
                                if(p(k,i))
                                {
                                                x[k]=i;
                                                if(k==n)
                                                {
                                                                printf("\n");
                                                                for(int j=1;j<=n;j++)
                                                                                printf("\t %d",x[j]);
                                                                printf("\n");
                                                                getch();
                                                                return;
                                                }
                                                else
                                                                n_queen(k+1,n);
                                }
                }
}
int p(int k,int i)
{
                for(int j=1;j<k;j++)
                                if((x[j]==i) || (abs(x[j]-i)== abs(j-k)))
                                                return 0;
                                                return 1;
}

Comments

Popular posts from this blog

How to create a custom form in wordpress

My new Jquery Plugin name is krDailog