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
!!!!
关于汉诺塔问题三
最新推荐文章于 2025-02-13 15:12:12 发布