-
Notifications
You must be signed in to change notification settings - Fork 0
/
8queen-all.c
74 lines (63 loc) · 1.69 KB
/
8queen-all.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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define NUM_OF_QUEEN 8
#define SIZE 8
typedef int Pos;
void display(Pos queens[NUM_OF_QUEEN], int size)
{
// print
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++) {
if (queens[y] == x)
printf("Q");
else
printf("_");
}
printf("\n");
}
}
bool canPut(Pos queens[NUM_OF_QUEEN], Pos newQueen, int numOfOnBoard)
{
for (int y = 0; y < numOfOnBoard; y++) {
Pos relative = newQueen - queens[y];
// vertical line or horizontal line or some pos
if (relative == 0 || numOfOnBoard - y == 0)
return false;
// forward slash or back slash
if (abs(relative) == abs(numOfOnBoard - y))
return false;
}
return true;
}
int count = 0;
bool backtracking(Pos *queens, int num_of_queens, int board_size, int numOfOnBoard)
{
// every rescursive we solve one row
// so this rescursive will chose one column
if (numOfOnBoard >= num_of_queens) {
// basecase
printf("--------\n");
count++;
display(queens, SIZE);
return false;
} else {
// chose one column
for (int x = 0; x < board_size; x++) {
if (canPut(queens, x, numOfOnBoard)) {
queens[numOfOnBoard] = x;
// next row
if (backtracking(queens, num_of_queens, board_size, numOfOnBoard + 1))
return true;
}
}
return false;
}
}
int main()
{
Pos queens[NUM_OF_QUEEN];
int i = backtracking(queens, NUM_OF_QUEEN, SIZE, 0);
printf("%d\n", count);
return 0;
}