汉诺塔 --递归
来源:互联网 发布:淘宝话费券在哪里 编辑:程序博客网 时间:2024/05/18 00:35
问题描述
Hanoi(汉诺)塔问题。这是一个古典的数学问题,是一个用递归方法解题的典型例子。古代有一个梵塔,塔内有3座A,B,C,开始时A座上有64个盘子,盘子大小不等,大的在下,
小的在上。有一个老和尚想把这64个盘子从A座移到C座,但每次只允许移动一个盘,且在移动过程中在3个座上都始终保持大盘在下,小盘在上。在移动过程中可以利用B座
,要求编程输出移动步骤
这里是谭浩强C语言书上的一道题 我是这样理解的
理解思路
所谓递归就是 调用 回归 假设有n个盘子 从A 移动到C 我们可以倒这来理解问题总有解决的办法 n-1个盘子已经全部都在B上 只要 将第n个盘子放到C盘上就OK了
解决了一个盘子 剩下n-1个盘子 在B盘上 (其实在那个盘上不重要 重要的是最后的结果 全在是C盘上 )于是可以做这样的假设把 A B两盘 调换位置 这样问题 又回到了
A盘有n-1个盘子 B盘没有 C盘有个最大的 我们又可以 反复进行 最终结果 在C盘上
代码
#include<stdio.h>void move(char x , char y){printf("%c-->%c\n",x,y); //输出 x->y }void hanoi(int n , char one , char two , char three) //n代表目前有n个盘子 one ,two,three 分别的位置是 three 是目的地 one 起始地 two是 中转站// 通过two 把 one 座的一个盘 移动到 three 座上 {if(n == 1){move(one,three);}else{//n-1个盘 借助 three 盘将 one 的n-1个盘移动到two座上 hanoi(n-1,one , three , two);//从one座 的一个盘子移动到 three上 move(one , three);//转换 two ,与one 使得 重新回到 one 座 n-1个盘 two座0个 three i个 (i表示递归次数) hanoi(n-1,two , one , three) ;}} int main(){int m ;printf("请输入有几个盘子\n"); scanf("%d",&m);hanoi(m,'A','B','C');return 0 ;}
#include<stdio.h>void move(char x , char y){printf("%c-->%c\n",x,y); //输出 x->y }void hanoi(int n , char one , char two , char three) //n代表目前有n个盘子 one ,two,three 分别的位置是 three 是目的地 one 起始地 two是 中转站// 通过two 把 one 座的一个盘 移动到 three 座上 {if(n == 1){move(one,three);}else{//n-1个盘 借助 three 盘将 one 的n-1个盘移动到two座上 hanoi(n-1,one , three , two);//从one座 的一个盘子移动到 three上 move(one , three);//转换 two ,与one 使得 重新回到 one 座 n-1个盘 two座0个 three i个 (i表示递归次数) hanoi(n-1,two , one , three) ;}} int main(){int m ;printf("请输入有几个盘子\n"); scanf("%d",&m);hanoi(m,'A','B','C');return 0 ;}
0 0
- 汉诺塔,递归&非递归
- 递归::汉诺塔
- 汉诺塔--递归
- 递归 -- 汉诺塔
- 汉诺塔(递归)
- 递归-汉诺塔
- 汉诺塔递归
- (递归)汉诺塔
- 汉诺塔-递归
- 汉诺塔:递归
- 汉诺塔 --递归
- 汉诺塔【递归】
- 递归-汉诺塔
- 递归汉诺塔
- 汉诺塔(递归)
- 递归汉诺塔
- 递归:汉诺塔
- 递归 & 汉诺塔
- 虚拟机怎么用 虚拟机安装教程
- 2014年值得关注的10个开源项目
- The import javax.servlet cannot be resolved
- 第7周【1】 深复制体验
- matlab中调用C和cmd命令
- 汉诺塔 --递归
- groovy中对象的比较以及非空判断
- GetSafeHwnd()和GetSafeHandle()的主要区别
- C#开发的类库dll,注册为Arcgis的插件tlb的方法
- 输入处理 Input Processor
- 日志分析方法概述
- 记载
- 我所接触过的编程语言
- 第五周作业——有向图邻接表表示及反向图构造