八皇后问题
#include <cstdio>
const int N = 8;
int count;
int notdanger(int row, int c, int (*chess)[N]) {
// i 和 j 是 行列下标,一直扫
// 列
for (int i = 0; i < N; i++) {
if (chess[i][c] != 0) {
return 0;
}
}
// 左上方
for (int i = row, j = c; i >= 0 && j >= 0; i--, j--) {
if (chess[i][j] != 0) {
return 0;
}
}
// 右下方
for (int i = row, j = c; i < N && j < N; i++, j++) {
if (chess[i][j] != 0) {
return 0;
}
}
// 右上方
for (int i = row, j = c; i >= 0 && j < N; i--, j++) {
if (chess[i][j] != 0) {
return 0;
}
}
// 左下方
for (int i = row, j = c; i < N && j >= 0; i++, j--) {
if (chess[i][j] != 0) {
return 0;
}
}
return 1;
}
void eight_queue(int row, int c, int (*chess)[N]) {
int chess2[N][N]; // 用于打印
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
chess2[i][j] = chess[i][j];
}
}
if (row == N) {
printf("%d\n", ++count); // 计算有 X 种方法
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%d ", chess2[i][j]);
}
printf("\n");
}
printf("\n\n");
} else { // 判断是否安全
for (int i = 0; i < c; i++) {
if ( notdanger(row, i, chess)) { // 不危险
for (int j = 0; j < N; j++) { // 因为这列以前被赋值过
chess2[row][j] = 0;
}
chess2[row][i] = 1;
eight_queue(row+1, c, chess2);
}
}
}
}
int main(void) {
int chess[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
chess[i][j] = 0;
}
}
eight_queue(0, N, chess);
return 0;
}