八皇后单解和全解递归算法

八皇后单解 递归算法


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

#define N 8

int num = 1;


int a[N] = { 0 };


void show()
{
    printf("Times %d\n", num++);
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (a[i] == j)
            {
                printf("X ");
            }
            else
            {
                printf("- ");
            }
        }
        printf("\n");
    }
    printf("\n");
}


int is_place_ok(int n, int c)
{
    for (int i = 0; i < n; i++)
    {
        if (a[i] == c || fabs(a[i] - c) == fabs(n - i))
        {
            return 0;
        }
    }
    return 1;
}

int mm = 0;

void add_queen(int n) //place the n_th queen n >= 0 and n < 8
{
    if (n >= N)
    {
        show();
    }
    else if (n < 0)
    {
        return;
    }
    else
    {

        for (; a[n] < N; a[n]++)
        {
            if (is_place_ok(n, a[n]))
            {
                break;
            }
        }
        if (a[n] < N)   //找到一个合适的位置 继续放置下一行皇后
        {
            a[n + 1] = 0;
            add_queen(n + 1);

        }
        else
        {
            //没找到 就回溯
            n--;
            a[n]++;
            add_queen(n);
        }

    }

}



void main()
{

    add_queen(0);


    system("pause");
}

八皇后全解 (92种解法) 递归算法


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

#define N 8

int num = 1;


int a[N] = {0};


void show()
{
    printf("Times %d\n", num++);
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (a[i] == j)
            {
                printf("X ");
            }
            else
            {
                printf("- ");
            }
        }
        printf("\n");
    }
    printf("\n");
}


int is_place_ok(int n, int c)
{
    for (int i = 0; i < n; i++)
    {
        if (a[i] == c || fabs(a[i] - c) == fabs(i - n))
        {
            return 0;
        }
    }
    return 1;
}


void add_queen(int n)
{

    if (n >= N)
    {
        show();
    }
    else
    {
        for (int c = 0; c < N; c++)
        {
            if (is_place_ok(n, c))
            {
                a[n] = c;
                add_queen(n + 1);
            }
        }
    }

}



void main()
{

    add_queen(0);


    system("pause");
}
    原文作者:八皇后问题
    原文地址: https://blog.csdn.net/rodbate/article/details/73699656
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞