Loading

N Queens Problem Iterative

C - Program to Implement N - Queens Problem (Iterative Solution)


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

#define TRUE 1
#define FALSE 0

void print_solution(int n,int x[])
{

    char c[10][10];
    int i,j;
    for(i=1;i<=n;i++)
    {
        for(j=1; j<=n; j++)
        {
            c[i][j]='-';
        }
    }

    for(i=1;i<=n;i++)
    {
        c[i][x[i]]='Q';
    }

    for( i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
            printf("\t%c",c[i][j]);
        }
            printf("\n");
    }

}


int place(int x[],int k)
{       int i;
    for(i=1;i<k;i++)
    {
        if(x[i]==x[k]||i-x[i]==k-x[k]||i+x[i]==k+x[k])
        {
            return FALSE;
        }
    }
    return TRUE;
}

void nqueens(int n)
{
    int x[10];
    int count=0;
    int k=1;

    x[k]=0;

    while(k!=0)
    {

        x[k]=x[k]+1;
        while((x[k]<=n)&&(!place(x,k)))
        {

            x[k]=x[k]+1;
        }
        if(x[k]<=n)
        {
            if(k==n)
            {
                count++;
                printf("\n\tSolution %d  is : \n\n\n",count);
                print_solution(n,x);

            }
            else
            {
                k++;
                x[k]=0;
                 }
        }
        else
        {
            k--;
        }
    }
    return;
}


void main()
{
    int n;
    clock_t start,end;
    clrscr();
    start=clock();
    printf("\n Enter the no. of Queens : ");
    scanf("%d",&n);
    printf("\n\n\t\t\t USING %d QUEEN'S STRATEGY \n\n",n);
    nqueens(n);
    end=clock();
    printf("\n The Time Complexity is : %f msec.",(end-start)/CLK_TCK);
    getch();
}

Click Here to Download Source Code with Executable Program.

Bookmark the permalink.

Leave a reply