#include <stdio.h>
#include <stdlib.h>
#define MAX_N 13
int solutionCount = 0;
// 打印解
void printSolution(int* solution, int n) {
for (int i = 0; i < n; ++i) {
printf("%d ", solution[i] + 1); //棋盘的列号是从1开始的
}
printf("\n");
}
// 检查是否可以放置皇后在当前列
int isValid(int* solution, int row, int col) {
for (int i = 0; i < row; ++i) {
if (solution[i] == col || abs(row - i) == abs(col - solution[i])) {//因为放了一个皇后之后就递归到下一行所以不需要判断是否等于row
return 0; // 不能放置
}
}
return 1; // 可以放置
}
// 递归求解 N 皇后问题
void solveNQueens(int* solution, int n, int row) {
if (row == n) {
// 找到一个解
solutionCount++;
if (solutionCount <= 3) {
printSolution(solution, n);
}
return;
}
for (int col = 0; col < n; col++) {
if (isValid(solution, row, col)) {
solution[row] = col;
solveNQueens(solution, n, row + 1);
solution[row] = -1; // 回溯
}
}
}
int main() {
int n;
scanf("%d", &n);
if (n <= 0 || n > MAX_N) {
printf("Invalid input\n");
return 1;
}
int* solution = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; ++i) {
solution[i] = -1; // 初始化为无效值
}
solveNQueens(solution, n, 0);
// 输出解的总数
printf("%d\n", solutionCount);
// 释放内存
free(solution);
return 0;
}
今天写累了,注释可能会晚点写,也可能不会,晚安