八皇后算法

八皇后问题
在一个8×8国际象棋盘上,有8个皇后,每个皇后占一格;要求皇后间不会出现相互“攻击”的现象,即不能有两个皇后处在同一行、同一列或同一对角线上。问共有多少种不同的方法。
#include
int line[8],answer=0;
void show()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
if(line[i]==j)
printf(“tQ”);
else
printf(“t*”);
}

printf(“nn”);
}
answer++;
printf(“nt%d ————-“,answer);
getchar();
}
int Judge(int t)
{
int i,n=0;
for(i=0;i<t;i++)
{
if(line[i]==line[t])
{n=1;break;}
if(line[i]+i==line[t]+t)
{n=1;break;}
if(line[i]-i==line[t]-t)
{n=1;break;}
}
return n;
}
void control(int n)
{
int t=8;
for(line[n]=0;line[n]<t;line[n]++)
{
if(Judge(n))
continue;
else
if(n!=7)
control(n+1);
else
show();
}
}
int main()
{
control(0);
printf(“%dn”,answer);
return 0;
}

9 thoughts on “八皇后算法

  1. To ALL LAODAs:
    代码已经改成c了,面向对象的后边在改写。

    To LILEI:
    使用pre标签,如果格式还乱这,就在可视化模式下,把代码选中,然后用规范的代码粘贴就可以了。

    Like

  2. #include
    #include
    #define n 8
    int a[n+1],c[n+1];
    int l[2*n],r[2*n+1];
    int count=0;
    void place(int);
    int main()
    {
    int k;
    for(k=1;k<=n;k++)c[k]=1;
    for(k=1;k<=2*n-1;k++)l[k]=1;
    for(k=2;k<=2*n;k++)r[k]=1;
    place(1);
    if(count==0) printf(“No Answer!n”);
    printf(“Program end.n”);
    getch();
    return 0;
    }
    void place(int i)
    {
    int j,k;
    for(j=1;j<=n;j++)
    {
    if((c[j]==1)&&(l[i-j+n]==1)&&(r[i+j]==1))
    {
    a[i]=j;
    c[j]=0;l[i-j+n]=0;r[i+j]=0;
    if(i<n) place(i+1);
    else
    {
    for(k=1;k<=n;k++)
    printf(“%4d”,a[k]);
    count++;
    printf(” count= %dn”,count);
    if(count%10==0) {printf(“Press any key to continue.n”);
    getch();}
    }
    c[j]=1;l[i-j+n]=1;r[i+j]=1;
    }
    }
    }

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.