[分享]hannoi塔的非递归算法
hannoi塔的非递归算法,我从杂志上无意中发现,大家分享.
#include<iostream>
using namespace std;
void shuchu(int m,int n)
{
for(int t=n,y=t&1,c=m;y-1;t=t>>1,y=t&1,c--);
switch((c&1)*3+(t>>1)%3)
{
case 0:cout<<n<<":A-B\n";break;
case 1:cout<<n<<":B-C\n";break;
case 2:cout<<n<<":C-A\n";break;
case 3:cout<<n<<":A-C\n";break;
case 4:cout<<n<<":C-B\n";break;
case 5:cout<<n<<":B-A\n";break;
}
}
void main()
{
int c=1,m,n=1;
cout<<"Input the number of the pale! 0-30"<<endl;
cin>>m;
cout<<"Move"<<m<<"pales:"<<endl;
for(c<<=m;n<c;n++)
shuchu(m,n);
}
画几个盘子的情况,分析步骤规律就出来了.