讨论汉诺塔之谜
2015-08-08 17:17
274 查看
汉诺塔是数学上的一个谜题。有三根杆子,一些不同大小的中间有孔的圆盘,可以按大小顺序套在杆子上,最小的在最上面,堆成类似锥形的结构。问题是怎么把一根杆子上的一堆圆盘移动到另一根杆子上,限定条件如下:
假设我们传递这样的参数:
输出如下:
Move disk 1 from peg A to peg B
Move disk 2 from peg A to peg C
Move disk 1 from peg B to peg C
Move disk 3 from peg A to peg B
Move disk 1 from peg C to peg A
Move disk 2 from peg C to peg B
Move disk 1 from peg A to peg B
注:代码不长,但理解代码的运行过程可能需要动一些脑筋,我在最后附上完整代码,或许你需要参考我前面的内容递归和内存分配(可视化)
一次只能移动一个圆盘。
每一次移动步骤包括将一根杆子最上面的圆盘移开放到另一根杆子上圆盘的最上层(不能动下面的盘子)。
所有大圆盘的下面不能有比他小的圆盘。
算法步骤(有n个圆盘,三根杆子分别为A,B,C,要将所有盘子从A上移动到B上)每一次移动步骤包括将一根杆子最上面的圆盘移开放到另一根杆子上圆盘的最上层(不能动下面的盘子)。
所有大圆盘的下面不能有比他小的圆盘。
将A上面的n-1个圆盘移动到C上。
将A上面最后一个圆盘移动到B上。
将C上面的n-1个圆盘移动到B上。
从C上移动n-1个圆盘到B上我们如法炮制。一旦我们解决n=3的情况,我们就能解决任何数量的盘子了。
将A上面最后一个圆盘移动到B上。
将C上面的n-1个圆盘移动到B上。
从C上移动n-1个圆盘到B上我们如法炮制。一旦我们解决n=3的情况,我们就能解决任何数量的盘子了。
void towerOfHanoi(int n, char fromPeg, char toPeg, char auxPeg) { //If only one disk, make a move and return :: base case if(n == 1) { printf("Move disk 1 from peg %c to peg %c ",fromPeg, toPeg); return; } //Move top n-1 disks from A to B, using C as auxiliary towerOfHanoi(n-1, fromPeg, auxPeg, toPeg); //Move remaining disks from A to C printf("\nMove disk %d from peg %c to peg %c ",n, fromPeg, toPeg); //Move n-1 disks from B to C using A as the auxiliary towerOfHanoi(n-1, auxPeg, toPeg, fromPeg); }
假设我们传递这样的参数:
towerOfHanoi(3, 'A'. 'B', 'C');
输出如下:
Move disk 1 from peg A to peg B
Move disk 2 from peg A to peg C
Move disk 1 from peg B to peg C
Move disk 3 from peg A to peg B
Move disk 1 from peg C to peg A
Move disk 2 from peg C to peg B
Move disk 1 from peg A to peg B
注:代码不长,但理解代码的运行过程可能需要动一些脑筋,我在最后附上完整代码,或许你需要参考我前面的内容递归和内存分配(可视化)
#include<stdio.h> #include<stdlib.h> /* Code obtained from http://www.studyalgorithms.com */ void towerOfHanoi(int n, char fromPeg, char toPeg, char auxPeg) { //If only one disk, make a move and return :: base case if(n == 1) { printf("Move disk 1 from peg %c to peg %c \n",fromPeg, toPeg); return; } //Move top n-1 disks from A to B, using C as auxiliary towerOfHanoi(n-1, fromPeg, auxPeg, toPeg); //Move remaining disks from A to C printf("Move disk %d from peg %c to peg %c \n",n, fromPeg, toPeg); /* Feel free to copy but please acknowledge studyalgorithms.com */ //Move n-1 disks from B to C using A as the auxiliary towerOfHanoi(n-1, auxPeg, toPeg, fromPeg); } int main(void) { printf("Enter the number of disks:- "); int disks; scanf("%d",&disks); towerOfHanoi(disks,'A','B','C'); return 0; }
相关文章推荐
- HDU 3360 National Treasures 奇偶匹配的最低点覆盖
- 内存管理中常见的问题
- php基于双向循环队列实现历史记录的前进后退等功能
- 守望者的逃离
- javaweb中利用filter进行修改字符集
- hpuoj 1868 寻宝【BFS】
- POJ 1644 放苹果 递推 递归
- HTML/CSS 选择符优先级
- [leetcode 236]Lowest Common Ancestor of a Binary Tree
- Topcoder SRM 663 Div2 Hard: CheeseRolling(状压DP)
- 2015 多校赛 第五场 1010 (hdu 5352)
- Uva 3027
- 奇因数求助,公式错了
- 关于Xcode7的Storyboard Reference
- 数据结构(总结版)
- 连通性小结(贴一些模板而已)
- C#模板引擎 RazorEngine3.7的扩展 — 引用布局页
- Spring AOP 实现原理
- iOS8下使用地图
- 找不到类FeatureQuery解决办法