8皇后

来源:互联网 发布:香港苹果mac pro价格 编辑:程序博客网 时间:2024/05/17 04:14

#include "stdio.h"
#include "string.h"

static int count=0;


int maze[20][20];
int prev[20];            // prev[i] represents the queue xpos in i ypos


int abs(int x)
{
    return x>0?x:-x;
}


bool can(int i,int j)    //i ypos  put j xpos
{
    for(int t=1;t<i;t++)
    {
        if( prev[t]==j || abs(prev[t]-j)==abs(t-i) )
            return false;
    }
    return true;
}

void queue(int n)
{
    if(n==9)
    {    count++;
        for(int t1=1;t1<=8;t1++)
        {    for(int t2=1;t2<=8;t2++)
                printf("%d",maze[t1][t2]);
            printf("/n");
        }

        printf("/n");
        printf("/n");
        printf("/n");
        printf("%d",count);
        printf("/n");
        printf("/n");
        printf("/n");
       

        return;
    }

    for(int i=1;i<=8;i++)
    {
        if( can(n,i) )
        {   
            prev[n]=i;
            maze[n][i]=1;
            queue(n+1);
            maze[n][i]=0;
            prev[n]=0;
        }

    }
}


int main()
{
    memset(maze,0,sizeof(maze));
    memset(prev,0,sizeof(prev));
    queue(1);
    return 0;
}

原创粉丝点击