关于汉诺塔问题三

来源:互联网 发布:社会学调查数据 编辑:程序博客网 时间:2024/05/17 03:08

int i = 0;

int ch;

while (k < max)  

{//按顺时针方向把圆盘1从现在的柱子移动到下一根柱子

ch = ta[i%3].Pop();

ta[(i+1)%3].Push(ch);

cout << ++k << ": " <<"Move disk " << ch << " from " <<

ta[i%3].name <<" to " << ta[(i+1)%3].name << endl;i++;

//把另外两根柱子上可以移动的圆盘移动到新的柱子上

if (k < max)

{//把非空柱子上的圆盘移动到空柱子上,当两根柱子都为空时,移动较小的圆盘

if (ta[(i+1)%3].Top() == 0 ||ta[(i-1)%3].Top() > 0 && ta[(i+1)%3].Top() > ta[(i-1)%3].Top())

{ ch =  ta[(i-1)%3].Pop();

ta[(i+1)%3].Push(ch);

 cout << ++k << ": " << "Move disk "<< ch << " from " <<

ta[(i-1)%3].name<< " to " << ta[(i+1)%3].name << endl;}

else

{ch =  ta[(i+1)%3].Pop();

ta[(i-1)%3].Push(ch);

cout << ++k << ": " << "Move disk "<< ch << " from " <<

ta[(i+1)%3].name<< " to " << ta[(i-1)%3].name << endl;}}}}

总结:算法其实很简单,至于关于汉诺塔的来源之类的就不说了,每一次借助另外一个转移掉,然后将最后的一个直接转移到C座位就可以了!下面是我的代码:

//汉诺塔问题

#include <iostream>

using namespace std;

int Hanoi(int n,char A,char B,char C)//参数:将A的碟子移动到C

{ if(n==1)

cout<<"Move the disk of "<<A<<" to "<<C<<";"<<endl

else

{

Hanoi(n-1,A,C,B);//先借助B转移n-1

cout<<"Move the disk of "<<A<<" to "<<C<<";"<<endl;

Hanoi(n-1,B,A,C);//再把B的转移到C

}//主要是这个地方的算法问题。

return 0;

}

int main()

{int n;

cout<<"Please enter the number of disk:";

cin>>n;

cout<<"Move "<<n<<" disk ,procdure is:"<<endl;

Hanoi(n,'A','B','C');

return 0;

}

先了解更多,去Google!!!!

原创粉丝点击