2n皇后问题

先判断一种皇后的放置方法,然后再去判断另一种皇后的放置方法代码如下

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int queue[10];
int queueB[10];
int sum = 0;
int table[10][10];

//用于测试第一种皇后的代码
void show(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (queue[i] == j)
                printf("M ");
            else
                printf("* ");
        }
        printf("\n");
    }
}
//用于测试第二种皇后的代码
void showB(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (queue[i] == j)
                printf("M ");
            else
                printf("* ");
        }
        printf("\n");
    }
}

//判断该位置能否放置第一种皇后
int check(int h)
{
    for (int i = 0; i < h; i++)
    {
        if (queue[i] == queue[h] || abs(queue[i] - queue[h]) == abs(i - h))
            return 0;
    }
    return 1;
}
//判断该位置能否放置第二种皇后
int checkB(int h)
{
    for (int i = 0; i < h; i++)
    {
        if (queueB[i] == queueB[h] || abs(queueB[i] - queueB[h]) == abs(i - h))
            return 0;
    }
    return 1;
}

//枚举寻找第二种皇后符合题意的方法
void queue_eightB(int a, int b)
{
    if (a < b)
    {
        for (int i = 0; i < b; i++)
        {
            if (table[a][i] == 1 && queue[a] != i)
            {
                queueB[a] = i;
                if(checkB(a))
                    queue_eightB(a + 1, b);
            }
        }
    }
    else
    {
        sum++;
        //show(b);
        //printf("@@@\n");
        //showB(b);
        //printf("----------------");
        //printf("\n\n");
    }

}
//枚举寻找第一种皇后的放置方法
void queue_eight(int m,int n)
{
    if (m < n)
    {
        for (int i = 0; i < n; i++)
        {
            if (table[m][i] == 1)
            {
                queue[m] = i;
                if (check(m))
                    queue_eight(m + 1,n);
            }
        }
    }
    else
        queue_eightB(0, n);
}


int main(void)
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            scanf("%d", &table[i][j]);
    queue_eight(0,n);

    printf("%d", sum);
}

 

posted @ 2021-01-19 11:29  loliconsk  阅读(159)  评论(0)    收藏  举报