四皇后问题

递归

#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;
}

posted @ 2014-07-30 17:12  liuzhijiang123  阅读(281)  评论(0编辑  收藏  举报