高效的八皇后问题非递归解法
2007-09-17 10:56
423 查看
//偶保存的一位以前上CSDN的高人写的, 稍慢 ...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
long count=0,ulim;
void slove( long row , long ld , long rd )
{
long pos,p;
if( row == ulim )
++count;
else for( pos = ulim&~(row|ld|rd);pos;p=pos&-pos,pos-=p,slove(row+p,(ld+p)<<1,(rd+p)>>1) )
;
}
int main(int argc, char *argv[])
{
int n = 8;
time_t bg ;
if( argc == 2&&(((n=atoi(argv[1]))<1||n>32)))
exit(1);
bg = time(NULL);
ulim = (1<<n)-1;
slove(0,0,0);
printf("N=%d,count=%d,time used=%d/n",n,count,(int)(time(NULL)-bg));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
long count=0,ulim;
void slove( long row , long ld , long rd )
{
long pos,p;
if( row == ulim )
++count;
else for( pos = ulim&~(row|ld|rd);pos;p=pos&-pos,pos-=p,slove(row+p,(ld+p)<<1,(rd+p)>>1) )
;
}
int main(int argc, char *argv[])
{
int n = 8;
time_t bg ;
if( argc == 2&&(((n=atoi(argv[1]))<1||n>32)))
exit(1);
bg = time(NULL);
ulim = (1<<n)-1;
slove(0,0,0);
printf("N=%d,count=%d,time used=%d/n",n,count,(int)(time(NULL)-bg));
return 0;
}
相关文章推荐