一、问题描述
参见网上汉诺塔的玩法。书上P54-58。解析:栈的递归调用其实是函数参数是以栈的形式push进栈来调用函数的,因此递归是用到栈的,只是没有很形象而已。解决汉塔的思路是这样的:设n为汉诺塔的盘子数,xyz是三根柱子。要让z有n个盘子的做法,先是将x的n-1个盘子移到y,然后将第n个盘子移到z,就这样的思路进行下去,最后就可以把汉诺塔的问题解决了。
二、算法实现
int c = 0;
void move(char x,int n,char z){
printf("%d Move dist %d from %c to %c \n",++c,n,x,z);
}
void hanoi(int n,char x,char y,char z){
//汉诺塔的盘的个数n x,y,z分别是柱子
if (n == 1)
{
//移动一个情况下 直接移动
move(x, 1, z);//将1号圆盘 从x放到z
}
else{
hanoi(n-1,x,z,y);//将x上的n-1个盘子 放到y上
move(x,n,z);//然后将第n个盘子放到z上
hanoi(n-1,y,x,z);//将y上的n-1个盘子放到z上
}
}
三、执行
//汉诺塔
hanoi(3, 'x', 'y', 'z');
输出:
1 Move dist 1 from x to z
2 Move dist 2 from x to y
3 Move dist 1 from z to y
4 Move dist 3 from x to z
5 Move dist 1 from y to x
6 Move dist 2 from y to z
7 Move dist 1 from x to z
请按任意键继续. . .