-
Notifications
You must be signed in to change notification settings - Fork 0
/
N_Queen.c
41 lines (36 loc) · 838 Bytes
/
N_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
#include <stdio.h>
#include <stdbool.h>
#define N 8
int board[N], d[N], e[2 * N - 1], f[2 * N - 1];
bool solve(int c) {
if (c == N) {
return true;
}
for (int i = 0; i < N; i++) {
if (!d[i] && !e[c + i] && !f[c - i + N - 1]) {
board[c] = i, d[i] = e[c + i] = f[c - i + N - 1] = 1;
if (solve(c + 1)) return true;
d[i] = e[c + i] = f[c - i + N - 1] = 0;
}
}
return false;
}
void printSolution() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i] == j)
printf("Q ");
else
printf(". ");
}
printf("\n");
}
}
int main() {
if (solve(0)) {
printSolution();
} else {
printf("Solution does not exist.\n");
}
return 0;
}