8皇后问题的解法实例代码

时间:2021-08-03 08:53:03
复制代码 代码如下:


#include <stdio.h>

 

#define MAX 200
#define Empty 0
#define Full 1
#define N 8

unsigned char qipan[N][N][N]={MAX};//初始化8张棋盘表示每下一步的
void input(int i);
int count = 0;

int main()
{
    input(0);
    getchar();
    return 0;
}
void input(int i)
{
    int x=0,y=0;
    int p=0,q=0;
    int flag = 0;
    //初始化当前棋盘
    if(i!=0)
    {
        for(x=0;x<N;x++)
        {
            for(y=0;y<N;y++)
            {
                qipan[i][x][y] = qipan[i-1][x][y];
            }
        }
    }
    else
    {
        for(x=0;x<N;x++)
        {
            for(y=0;y<N;y++)
            {
                qipan[i][x][y] = MAX;
            }
        }
    }
    //递归结束
    if(i==N)
    {
        count++;
        for(x=0;x<N;x++)
        {
            for(y=0;y<N;y++)
            {
                printf("%d ",qipan[i-1][x][y]);
            }
            printf("\n");
        }
        printf("%d\n",count);
        return;
    }

    for(y=0;y<N;y++)
    {
        //找到空位
        if(qipan[i][i][y]==MAX)
        {
            //另其为1
            qipan[i][i][y] = 1;
            //前后左右上下都置为0
            for(p=0;p<N;p++)
            {
                for(q=0;q<N;q++)
                {
                    if(q==y||p==i||(p-i)==(q-y)||(p-i)==(y-q))
                        if(qipan[i][p][q] == MAX)
                            qipan[i][p][q] = 0;
                }
            }
            if(flag != -1)
            {
                //找下一个
                input(i+1);
            }
            //将棋盘变回本层原样
            for(p=0;p<N;p++)
            {
                for(q=0;q<N;q++)
                {
                    if(i!=0)
                    qipan[i][p][q] = qipan[i-1][p][q];
                    else
                    qipan[i][p][q] = MAX;
                }
            }
            flag =0;
        }
    }
    //找不到空位结束
    return;
}