首页 > 代码库 > 四皇后问题

四皇后问题

递归

#include <stdio.h>#include <stdlib.h>#include <errno.h>#define NUM 4int total = 0;void print_board(int *board){    printf("\n");    for (int i = 0; i < NUM; i++)    {        for (int j = 0; j < NUM; j++)        {            printf("%4d", board[j] == i ? 1 : 0);        }        printf("\n");    }}int check(int *board, int col){    for (int i = 0; i < col; i++)    {        if (board[i] == board[col] || abs(board[i] - board[col]) == abs(i - col))        {            return 0;        }    }    return 1;}void queen(int *board, int col){    if (col == NUM)    {        print_board(board);        total++;        return;    }    for (int row = 0; row < NUM; row++)    {        board[col] = row;        if (check(board, col))        {            queen(board, col + 1);        }    }}int main(int argc, char **argv){    printf("total = %d\n", total);    int board[NUM];    for (int i = 0; i < NUM; i++)    {        board[i] = 0;    }    queen(board, 0);    printf("total = %d\n", total);    getchar();    return 0;}