四皇后问题

递归

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define NUM 4
int 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;
}

非递归:

#include <stdio.h>
#include <stdlib.h>
#define NUM 4
int 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 = 0;
    int row = 0;
    board[0] = 0;
    col = 1;
    while (col >= 0)
    {
        if (col == NUM)
        {
            print_board(board);
            col--;
            total++;
            continue;
        }
        int row = board[col];
        int result = 0;
        while (++row < NUM)
        {
            board[col] = row;
            result = check(board, col);
            if (result == 1)
            {
                break;
            }
        }
        if (row == NUM)
        {
            board[col] = -1;
            col--;
            continue;
        }
        else
        {
            col++;
            continue;
        }
    }
}

int main(int argc, char **argv)
{
    //printf("total = %d\n", total);
    int board[NUM];
    for (int i = 0; i < NUM; i++)
    {
        board[i] = -1;
    }
    queen(board);
    printf("total = %d\n", total);
    getchar();
    return 0;
}

转载于:https://www.cnblogs.com/liuzhijiang123/p/3878531.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值