皇后问题的一个解法

来源:互联网 发布:博德之门 知乎 编辑:程序博客网 时间:2024/04/30 14:23

#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秒