Thursday, 12 February 2015

NQueen Problem in C



 NQueen Problem in C



 




#include<stdio.h>
#include<math.h>
#define TRUE 1
#define FALSE 0
#define MAXBOARDSIZE 8
int board[MAXBOARDSIZE];
int n;
int steps;
static int solno=1;
void PrintBoard()
{
    int i, k,z;

    printf("\nSolution %d:\n", solno++);
    printf("No of Steps=%d:\n", steps);
    for (i = 0; i < n; i++)
    {
        for (k = 0; k < board[i]; k++)
            printf("\t-");
        printf("\tQ%d",i+1);
        for(z=k;z<n-1;z++)
            printf("\t-");
        printf("\n");
    }
}

int IsPlaceSafe(int row, int col)
{
    int i;

    for(i=0; i<row; i++)
    {
        if( (board[i] == col) || (abs(board[i]-col) == abs(i-row)) )
            return FALSE;
    }
    return TRUE;
}

void NQueens(int row)
{
    int col;
    for(col=0; col<n; col++)
    {
        steps++;
        if(IsPlaceSafe(row, col))
        {
            board[row] = col;
            if(row == n-1)
                PrintBoard();
            else
                NQueens(row+1);
        }
    }
}

int main()

    int c=1;
    while(c==1){
    printf("Enter board size: ");
    scanf("%d", &n);
    if(n>MAXBOARDSIZE || n<4){
     printf("\nNo Solution Exit\n");
    }else{
    NQueens(0);
    }
    printf("\nPress 1 to Continue and 0 to exit");
    scanf("%d",&c);
    solno=1;
    steps=0;
    }
    return 0;
}

0 comments:

Post a Comment