标题: [分享]hannoi塔的"牛"算法--非递归 [打印本页] 作者: 烟灰缸2 时间: 2009-11-3 23:54 标题: [分享]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) //c&1ê??????D??£?t>>1ê?2??Dμ?Dòo??£
{
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; //n?aò??ˉ?ì×ó2??èμ?Dòo??£
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);
}