#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#define N 8
bool conflict(int state[], int nextColumn) {
int nextRow = 0;
while (state[nextRow] != -1 && nextRow < N) {
nextRow++;
}
for (int row = 0; row < nextRow; row++) {
int column = state[row];
// 检查是否在同一列或对角线上
if (abs(column - nextColumn) == 0 ||
abs(column - nextColumn) == nextRow - row) {
return true;
}
}
return false;
}
void prettyprint(int solution[]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (solution[i] == j) {
printf("X ");
} else {
printf(". ");
}
}
printf("\n");
}
}
void queens(int row, int state[], int *count) {
if (row == N) { // 9
(*count)++;
printf("第%d种解决方案:\n", *count);
for (int i = 0; i < N; i++) {
printf("%d ", state[i]);
}
printf("\n");
prettyprint(state);
printf("**************************************************\n");
return;
}
for (int col = 0; col < N; col++) {
if (!conflict(state, col)) {
state[row] = col;
queens(row + 1, state, count);
state[row] = -1; // back
}
}
}
int main() {
int state[N];
for (int i = 0; i < N; i++) {
state[i] = -1;
}
int count = 0;
queens(0, state, &count);
printf("总共找到 %d 种解决方案\n", count);
return 0;
}
[Note]C 八皇后解法
发布于 21 天前 最后更新于 21 天前 160 次阅读
Comments NOTHING