8皇后代码,abs在stdlib中,不在math中


#include <stdio.h>
#include <math.h>
#include<stdlib.h>
#include <memory.h>

#define ROW      8
#define COLUMN   ROW

int success = 0;    /*successful times*/

void show(int* p)
{
   int i = 0;
    printf("%2d>>> ", success);
   for (i=0;i<COLUMN ; i++ )
    {
        printf("%d, ", p[i]);
    }
    printf("/n");
}
int main(int argc, char *argv[])
{
    int pieces[COLUMN];
   int row      = 0;        /*row in the first column*/
       int column   = 0;        /*the current column*/
           int flag     = 0;        /*is matched in current column*/
           int i        = 0;        /*row int current column*/
           int j        = 0;        /*column from 0 to the one before the current column*/
           int count    = 0;        /*steps need*/
    /*set the pieces all as -1, [0,COLUMN) represents row in the n-th column*/
     memset(pieces, -1, sizeof(pieces));
    //init (0,0) as 0, and the current column add to the next column
    pieces[column]     = 0;
    column++;
   
    while (row < ROW)
   {
        while (column < COLUMN)
        {
           count++;
           flag = 0;
           i = pieces[column] + 1;
//          if (i>=ROW && column==1)
//              break;
//          else if (column==0 && i>5)
//              break;

            for (i=i; i<ROW ;i++ )
            {
                for (j=0 ;j<column ;j++ )
               {
                    if (i==pieces[j] || abs(j-column)== abs(pieces[j]-i))
                    {
                        flag = 0;
                        break;
                    }
                    flag = 1;
                }
                if (flag)
                    break;
            }
            if (flag)
            {
                pieces[column] = i;
                column++;
            }
            else
                     {
                pieces[column] = -1;
               column--;
                if (column == 0)  /*nowhere to go back*/
                             break;
            }
        }/*internal while end*/
          if (flag)
        {
            success++;
            show(pieces);
            flag = 0;
            pieces[column-1]   = -1;
            column   -= 2;
        }
        else
               {
            memset(pieces, -1, sizeof(pieces));
            column = 0;
            row++;
            pieces[column] = row;
            column++;
        }
    }/*external while end*/
    printf("总共步数:%d/nPress Any Key to Continue.../n", count);
  //  fflush(stdin);
    system("pause");;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值