8 황후 문제 의 해법 실례 코드

2357 단어 황후해법

#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("
");
        }
        printf("%d
",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;
}

좋은 웹페이지 즐겨찾기