大一的时候学C语言时,在递归部分讲过汉诺塔问题,但那时只是勉强懂了而已,没有上机实验,在三年后,终于重新拾起了这个问题,并且写了程序跑了跑,不错,感觉挺清楚了。也更加地理解了递归:
现在总结一下:
要 将柱A的n个盘子通过柱B全部移到柱C:
步骤可拆分下:
- 将柱A上面n-1个盘子通过柱C全部移到柱B;
- 将柱A上1的第n个盘子直接移动到C
- 将柱B上面n-1个盘子通过柱A全部移到柱C;
代码如下:
#include<stdio.h>
/*
Name: tower of Hanoi
Copyright:
Author: demosees
Date: 22/03/17 22:00
Description: transfer n dishes from 1 to 3 via 2 with 1 dish a time.the big dish
must always be under the small;
*/
void Move(int n,int start,int temp,int goal)/*solved by recursion*/
{
/*termination condition*/
if (n==1)
printf("Move disk %d from %d to %d\n",n,start,goal);
else
{
Move(n-1,start,goal,temp);/*transfer n-1 form 1 to 2 via 3*/
printf("Move disk %d from %d to %d\n",n,start,goal);/*transfer the n"th" from 1 to 3*/
Move(n-1,temp,start,goal);/*transfer n-1 form 2 to 3 via 1*/
}
}
int main()
{
int n;
/*input the number of dishes*/
scanf("%d",&n);
/*call the function*/
Move(n,1,2,3);
return 0;
}