05:52
NQueen problem code in c:

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

//for a NXN chess board
#define N 4

int x[N]={-1,-1,-1,-1}; //array of queen positions

void nqueen(int K, int n);
bool place(int k, int i);
int abs(int a);
void write();

void main()
{
printf("\nIt's a N-Queen chess board problem\n");

nqueen(0,N);
}


void nqueen(int k,int n)
{
   int i;
    for(i=0;i<n;i++)
    {
        if(place(k,i))
           {
               x[k]=i;

               if(k==N-1)
                {
                    printf("\nThese are the co-ordinates of safe positions for %d queens\n",N);
                    write();
                    exit(0);
                }
                else
                {

                nqueen(k+1,n);
                }
           }
    }
}
bool place(int k, int i)
{
   int j;
    for(j=0;j<=(k-1);j++)
    {
       //doing column & diagonal check
        if((x[j]==i)||abs(x[j]-i)==abs(j-k))
        return false;
    }
    return true;
}
//absolute function
int abs(int a)
{
return (a<0)?-a:a;
}
void write()
{
    int a;
    for(a=0;a<N;a++)
    printf("(%d,%d)\t",a,x[a]);

}


OUTPUT:
It's a N-Queen chess board problem
These are the co-ordinates of safe positions for 4 queens:
(0,1) (1,3) (2,0) (3,2)



0 comments: