N皇后问题代码求讲解
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;
if(row==0&&p>half)
continue;
else
test(row + p, (ld + p) << 1, (rd + p) >> 1);
}
}
else
{
sum++;
}
}
int main(int argc, char *argv[])
{
time_t tm;
int n;
printf("请输入皇后个数 N [ 0<n<32 ]:");
scanf("%d",&n);
if (argc != 1)
n = atoi(argv[1]);
tm = time(0);
if ((n < 1) || (n > 32))
{
printf("该程序只能计算1到32\n");
exit(-1);
}
if(n==1)
{
sum=1;
printf("共有%ld种放法. \n花费时间为%.12lf秒. \n", sum, (int)(time(0) - tm));
return 0;
}
printf("完成%d皇后问题可能花费一点时间,请耐心等待...\n", n);
half=(n-1)/2;
half=upperlim<<half;
upperlim = (upperlim << n) - 1;
test(0, 0, 0);
printf("共有%ld种放法. \n花费时间为%d秒. \n", sum*2, (int)(time(0) - tm));
return 0;
}
求解释