Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: n-Queen

Saturday, August 10, 2013

n-Queen

n-queens problem of placing n queens on an n×n chessboard, where solutions exist for all natural numbers n with the exception of n=2 and n=3.


#include<stdio.h>
#include<malloc.h>
#define TRUE 1
#define FALSE 0

int BOARDSIZE;
int DIAGONAL;
int OFFSET;
void dispal(void);
void add_queen(void);
int *queencol;
int *colfree;
int *upfree;
int *downfree;
int Queenc=-1;
int main()
{
int i;
printf("\n Enter the boardsize: ");
scanf("%d",&BOARDSIZE);
DIAGONAL=2*BOARDSIZE-1;
OFFSET=BOARDSIZE-1;
queencol=(int *)malloc(BOARDSIZE*sizeof(int));
colfree=(int *)malloc(BOARDSIZE*sizeof(int));
upfree=(int *)malloc(DIAGONAL*sizeof(int));
downfree=(int *)malloc(DIAGONAL*sizeof(int));
for(i=0;i<BOARDSIZE;i++)
    colfree[i]=TRUE;
    //queencol[i]=-1;
for(i=0;i<DIAGONAL;i++)
    {
    upfree[i]=TRUE;
    downfree[i]=TRUE;
    }
add_queen();
return 0;
}
void add_queen(void)
    {
    int col;
    Queenc++;
    for(col=0;col<BOARDSIZE;col++)
        if(colfree[col] && upfree[Queenc+col] && downfree[Queenc-col+OFFSET])
            {
            queencol[Queenc]=col;
            colfree[col]=FALSE;
            upfree[Queenc+col]=FALSE;
            downfree[Queenc-col+OFFSET]=FALSE;
            if(Queenc==BOARDSIZE-1)
                display();
            else
                add_queen();
            colfree[col]=TRUE;
            upfree[Queenc+col]=TRUE;
            downfree[Queenc-col+OFFSET]=TRUE;
            }
        Queenc--;
    }
void display(void)
    {
    printf("\n");
    int i,j,tmp;
    for(i=0;i<BOARDSIZE;i++)
        {
        tmp=queencol[i];
        for(j=0;j<BOARDSIZE;j++)
            {
            if(j==tmp)
            printf(" Q ");
            else
            printf(" 0 ");
            }
        printf("\n");
        }
    printf("\n");
    return;
    }
 

No comments:

Post a Comment