N – Queens Problem

#include<stdio.h>

void nqueen(int,int);
int place(int,int);
int x[100],c=1;

void main()
{
    int n;
    printf("Enter the number of queens: ");
    scanf("%d",&n);
    printf("\n");
    nqueen(1,n);
    printf("Total solution for N=%d --> %d",n,c-1);
}

void nqueen(int k,int n)
{
    int i,j,l,count;
    for(i=1;i<=n;i++)
    {
        if(place(k,i))
        {
            x[k]=i;
            if(k==n)
            {
                printf("%d\n",c++);
                count=1;
                for(j=1;j<=n;j++)
                {
                    for(l=1;l<=n;l++)
                    {
                        if(j==count&&l==x[count])
                        {
                            printf("Q");
                            count++;
                        }
                        else
                        {
                            printf("-");
                        }
                    }
                    printf("\n");
                }
                printf("\n");
            }
            else
                nqueen(k+1,n);
        }
    }
}

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

/*output
Enter the number of queens: 4

1
-Q–
—Q
Q—
–Q-

2
–Q-
Q—
—Q
-Q–

Total solution for N=4 –> 2
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s