N個皇后算法

#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 = 16;

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

test(
0, 0, 0);
printf("共有%ld種排列, 計算時間%d秒  ", sum, (int) (time(0- tm));
}
 具體參見
http://community.csdn.net/Expert/TopicView3.asp?id=4709025
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章