汉诺塔递归算法

来源:互联网 发布:mac os 镜像下载 编辑:程序博客网 时间:2024/04/28 15:51
static void move(char x,char y){   cout<<x<<"--->"<<y<<endl;}static void hanoi(int n,char one,char two,char three){  if(n==1) move(one,three);  else{    hanoi(n-1,one,three,two);    move(one,three);    hanoi(n-1,two,one,three);  }}void main(){  int n;  printf("input the number of diskes:");  scanf("%d",&n);  printf("The step to moving %3d diskes:\n",n);  hanoi(n,'A','B','C');}

算法思想:
A、B、C三个桌子,A上有n个盘子要全部移动到C上,只需按照一下步骤:
1、将A上面的n-1个盘子移动到B上;
2、将A上剩下的一个盘子移动到C上;
3、将B上的n-1个盘子移动到C上。
                                             
0 0