编辑代码

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define N 8

void printSolution(int board[N]);
bool isSafe(int board[N], int row, int col);
bool solveNQUtil(int board[N], int col);

/* 打印解决方案 */
void printSolution(int board[N]) {
    static int solutionNumber = 1;
    printf("Solution #%d:\n", solutionNumber++);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            // 打印 'Q' 或 '.'
            printf("%c ", board[i] == j ? 'Q' : '.');
        }
        printf("\n");
    }
    printf("\n");
}

/* 检查皇后摆放是否安全 */
bool isSafe(int board[N], int row, int col) {
    int i, j;
    for (i = 0; i < col; i++)
        if (board[i] == row)
            return false;

    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
        if (board[j] == i)
            return false;

    for (i = row, j = col; j >= 0 && i < N; i++, j--)
        if (board[j] == i)
            return false;

    return true;
}

/* 递归函数解决N皇后问题 */
bool solveNQUtil(int board[N], int col) {
    /* 所有皇后都放置完毕,则返回true */
    if (col >= N) {
        printSolution(board);
        return true;
    }

    bool res = false;
    for (int i = 0; i < N; i++) {
        /* 检查皇后是否可以放在board[i][col] */
        if (isSafe(board, i, col)) {
            board[col] = i;
            res = solveNQUtil(board, col + 1) || res;
            /* 如果放置皇后导致解决不了问题,则回溯 */
            board[col] = -1; // 可选
        }
    }
    /* 如果皇后没有地方可以放置 */
    return res;
}

/* 解决N皇后问题 */
bool solveNQ() {
    int board[N];
    for (int i = 0; i < N; i++) board[i] = -1;

    if (solveNQUtil(board, 0) == false) {
        printf("Solution does not exist");
        return false;
    }

    return true;
}

/* main函数 */
int main() {
    solveNQ();
    return 0;
}