Thursday, 13 September 2012

N Queen Problem Implementation


/*N queen problem*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define max 100

void display(int array[max],int size)
{
    int ctr=0;
    printf("Next set of possible coordinates:\n");
    while(ctr<size)
    {
        printf("(%d,%d)\t",ctr+1,array[ctr]+1);
        ctr++;
    }
    printf("\n");
}

int isAValidPosition(int position[max],int row,int column)
{
    int ctr=0;
    while(ctr<row)
    {
        if( column==position[ctr] || abs(ctr-row)==abs(column-position[ctr]))
        return 0;
        ctr++;
    }
    return 1;
}

void nQueen(int position[max],int n,int row)
{
    int i;
    if(row>=n)
    {
        display(position,n);
    }
    else
    {
        for(i=0;i<n;i++)
        {
            if(isAValidPosition(position,row,i))
            {
                position[row]=i;
                nQueen(position,n,row+1);
            }
        }
    }
}

int main()
{
    int positions[max];
    nQueen(positions,4,0);
    /*First parameter is the array containing the valid coordinates.
    Second parameter is the value of n; currently its 4 queen
    Third parameter is the starting row, which is always 0.*/
    system("pause");
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
@Gnosioware Solutions