八皇后问题(搜索)

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

int queue[8];
int sum = 0;
void show()
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            if (queue[i] == j)
                printf("M ");
            else
                printf("* ");
        }
        printf("\n");
    }
}

int check(int k)
{
    for(int row = 0;row<k;row++)
        if(queue[row] == queue[k] || abs(queue[row]-queue[k]) == abs(k-row ))
            return 0;
    return 1;
}

void queue_eight(int n)
{
    if (n < 8)
    {
        for(int i = 0;i<8;i++)
        {
            queue[n] = i;
            if (check(n))
                queue_eight(n + 1);
        }
    }
    else
    {
        printf("this is %d\n", ++sum);
        show();
    }
}

int main(void)
{
    queue_eight(0);
    return 0;
}

 

posted @ 2021-01-18 15:47  loliconsk  阅读(79)  评论(0)    收藏  举报