-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8_queen.c
84 lines (73 loc) · 1.73 KB
/
8_queen.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
#include <stdio.h>
#define TRUE 1
#define FALSE 0
static short int board[8][8];
int good(int row, int col) {
// Check the row
for (int i = 0; i < 8; i++) {
if (board[row][i] && i != col) {
return FALSE;
}
}
// Check the column
for (int i = 0; i < 8; i++) {
if (board[i][col] && i != row) {
return FALSE;
}
}
// Check the upper-left diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] && (i != row || j != col)) {
return FALSE;
}
}
// Check the upper-right diagonal
for (int i = row, j = col; i >= 0 && j < 8; i--, j++) {
if (board[i][j] && (i != row || j != col)) {
return FALSE;
}
}
return TRUE;
}
void drawboard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board[i][j] == TRUE) {
printf("Q ");
} else {
printf(". ");
}
}
printf("\n");
}
printf("\n");
}
int try(int n) {
if (n == 8) {
return TRUE; // All queens have been successfully placed.
}
for (int i = 0; i < 8; i++) {
if (good(n, i)) {
board[n][i] = TRUE;
if (try(n + 1)) {
return TRUE;
}
board[n][i] = FALSE;
}
}
return FALSE;
}
int main() {
int i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
board[i][j] = FALSE;
}
}
if (try(0) == TRUE) {
drawboard();
} else {
printf("No solution found.\n");
}
return 0;
}