language: C (gcc-4.7.2)
date: 276 days 22 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
 
int isSafe(int k,int i,int *x)
{
        int j;
        for(j=0;j<k;j++)
        {
                  //old queen is placed at jth row of x[j] column
                  //new queen to be placed at kth row of ith column
                if(i==x[j] || abs(k-j)==abs(i-x[j]))
                        return 0;
        }
        return 1;
}
 
void printSol(int* sol, int N)
{
        int row;
 
        for( row = 0; row < N; ++row )
                printf("%d ",sol[row]);
}
 
int Nqueen(int k, int* sol, int N)
{
        int col;
        if( k == N )
        {
                printSol(sol,N);
                return 1;
        }
        else
        {
                for(col = 1;col <= N; col++)  //determines appropriate column number of the kth queen to be placed
                {
                        if( isSafe(k,col,sol) )
                        {
                                sol[k] = col;
                                if( Nqueen(k+1, sol, N) )
                                        return 1;
                                // sol[k] = 0;
                        }
                }
                return 0;
        }
}
 
int main()
{
        int sol[8], N = 8;
        Nqueen(0,sol,N);
 
        return 0;
}