算法:汉诺塔(栈的递归调用)-数据结构(9)

来源:互联网 发布:央视网络电视台官网 编辑:程序博客网 时间:2024/06/01 20:06

一、问题描述

参见网上汉诺塔的玩法。书上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 z2 Move dist 2 from x to y3 Move dist 1 from z to y4 Move dist 3 from x to z5 Move dist 1 from y to x6 Move dist 2 from y to z7 Move dist 1 from x to z请按任意键继续. . .




阅读全文
0 0
原创粉丝点击