皇后问题的一个解法


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

long sum=0,upperlim=1;

void test(long row, long ld, long rd){

if (row != upperlim){
long pos = upperlim & ~(row | ld | rd);
while (pos){
long p = pos& -pos;
pos -= p;
test(row+p, (ld+p)<<1, (rd+p)>>1);
}}
else
sum++;
}

int main(int argc, char *argv[])
{
time_t tm;
int n=8;

if(argc!=1)n=atoi(argv[1]);
tm=time(0);
if((n<1)||(n>32)){
printf(" 只能计算1-32之间/n");
exit(-1);}
printf("%d 皇后/n",n);
upperlim=(upperlim<<n)-1;

test(0,0,0);
printf("共有%ld种排列, 计算时间%d秒 /n", sum,(int)(time(0)-tm));
}


10 皇后
共有724种排列, 计算时间0秒

11 皇后
共有2680种排列, 计算时间0秒

12 皇后
共有14200种排列, 计算时间0秒

13 皇后
共有73712种排列, 计算时间0秒

14 皇后
共有365596种排列, 计算时间1秒

15 皇后
共有2279184种排列, 计算时间5秒


16 皇后
共有14772512种排列, 计算时间30秒

17 皇后
共有95815104种排列, 计算时间224秒
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值