-
Notifications
You must be signed in to change notification settings - Fork 0
/
nQueens.c
58 lines (57 loc) · 1015 Bytes
/
nQueens.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
#include <stdio.h>
#include <stdlib.h>
int x[10];
static int c = 1;
void printBoard(int n)
{
int i, j;
printf("Solution %d:\n", c++);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (x[i] == j)
printf("Q\t");
else
printf("-\t");
}
printf("\n");
}
}
int place(int k, int i)
{
int j;
for (j = 1; j < k; j++)
{
if ((x[j] == i) || abs(x[j] - i) == abs(j - k))
return 0;
}
return 1;
}
void nQueens(int k, int n)
{
int i, j;
for (i = 1; i <= n; i++)
{
if (place(k, i))
{
x[k] = i;
if (k == n)
{
printf("\n");
printBoard(n);
}
else
nQueens(k + 1, n);
}
}
}
int main()
{
int n;
printf("Enter the number of queens:\n");
scanf("%d", &n);
nQueens(1, n);
if (c == 1)
printf("No solutions!");
}