forked from harsimrans/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnqueen.c
144 lines (119 loc) · 1.95 KB
/
nqueen.c
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/******************************************
*
* N Queens Problem
*
* Harsimran Singh
*
* Prints the board arrangement which are
* solutions to N queens problem
*
******************************************/
#include<stdio.h>
//100 x 100 boards max as of now
int x[100] = {0, 3, 5, 2, -1, -1};
void NQ(int k, int n);
int diagonal(int i, int j, int n);
int place(int i, int j, int n);
void display(int n);
int numSol = 0;
int main()
{
int n, i;
printf("Enter the dimension of board : ");
scanf("%d", &n);
for (i = 0 ; i < n; i++)
x[i] = -1;
numSol = 0;
NQ(0, n);
printf("sols : %d\n", numSol);
return 0;
}
void NQ(int k, int n)
{
//printf("NQ called\n");
int i;
for (i = 0 ; i < n; i++)
{
if (place(k, i, n) == 1)
{
x[k] = i;
if(k == n-1)
{
//int j;
printf("SOLUTION\n");
numSol++;
display(n);
printf("\n");
}
else
NQ(k+1, n);
}
}
/*
if(x[k] == -1)
{
x[k-1] = -1;
}
*/
}
int place(int i, int j, int n)
{
//printf("called for : %d %d\n",i , j );
//check for the column
int m;
for (m = 0; m < i; m++)
{
if (x[m] == j)
{
// printf("Column violation\n");
return -1;
}
}
//printf("Checked for column\n");
//check diagonal
int b = diagonal(i, j, n);
if (b == -1)
return -1;
return 1;
}
int diagonal(int i, int j, int n)
{
int z, y;
z = i;
y = j;
//check up-left
while (--z >= 0 && --y >= 0)
{
if (x[z] == y)
{
return -1;
}
}
//check up-right
z = i;
y = j;
while (--z >= 0 && ++y < n)
{
if (x[z] == y)
{
return -1;
}
}
return 1;
}
void display(int n)
{
int i, j;
for (i=0; i < n; i++)
{
for(j = 0 ; j < n; j++)
{
if (x[i] == j)
printf("Q ");
else
printf("# ");
}
printf("\n");
}
}