精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>C/C++>>算法集锦--------梦入玄机>>八皇后问题算法>>Re: 八皇后问题的解(回溯法程序代码)

主题:Re: 八皇后问题的解(回溯法程序代码)
发信人: zhzhzzx@GZ()
整理人: yangcs(2002-01-14 18:36:29), 站内信件

标  题: Re: 八皇后问题的解(回溯法程序代码)
发信站: 网易虚拟社区 (Fri Jul 14 11:06:45 2000), 站内信件

【 在 tabalulu (taba&lulu) 的大作中提到: 】
: 以前上学的时候,写8皇后程序的时候偷懒用最笨的算法,在8086上计算十皇后
: 的时候,我放了张纸条,说明计算机正在运行,然后去吃饭,吃完以后,才看到

: 结果。前几天,刚好有空,所以重写了一次,以补当年的遗憾。
:    .......

面向对象的c++程序, 回溯法, 请指点, 谢!

#include<iostream.h>
class heng
 {
  public:
   heng(int i):z(i){};
   void ty();
   int Total();
  private:
   void print();
   int z;
   static unsigned int y,j,l;
   static int sum[8];
   static int total;
 };
unsigned int heng::y=0;
unsigned int heng::j=0;
unsigned int heng::l=0;
int heng::sum[8]={0,0,0,0,0,0,0,0};
int heng::total=0;
void heng::ty()
 {
  for (int k=0; k<8; k++)
{
if (!(y&1<<k) && !(j&1<<(z+k)) && !(l&1<<(z-k+7)))
{
y|=1<<k;
j|=1<<z+k;
l|=1<<z-k+7;
sum[z]=k;
if (z<7)
{
heng *next=new heng(z+1);
next->ty();
 delete next;
}
       else
{
 print();
 total+=1;
}
      y&=~(1<<k);
j&=~(1<<z+k);
l&=~(1<<z-k+7);
}
}
}
void heng::print()
{
for (int k=0; k<8; k++)
cout<<sum[k]+1<<' ';
cout<<endl;
}
int heng::Total()
{
return total;
}
class app
{
public:
int run();
private:
heng *next;
};
int app::run()
{
next=new heng(0);
next->ty();
  cout<<"Total="<<next->Total();
  delete next;
  return 0;
 }
int main()
 {
  app a;
  return a.run();
 }

--
※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 202.104.39.110]

[关闭][返回]