当前位置:网站首页>递归实现汉诺塔问题
递归实现汉诺塔问题
2022-07-31 04:00:00 【GD_small_bit】
我今天带来了汉诺塔的C语言实现代码。
汉诺塔(Tower of Hanoi),又称河内塔,是一个源于印度古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
如下有三根柱子:
游戏规则如下:在a柱上会有n个盘子,并且盘子大的在下面,盘子小的在上面,每次只能移动一个盘子,直到把盘子按从大到小在c柱子往上排列起来。
假设盘子只有一个,那我们直接把盘子从a柱移到了c柱,即a->c。
假设a柱上的盘子有两个,那我们应当将盘子较小的移到b柱,再将盘子较大的移到c盘,再将b柱上的盘子移到c柱,即 a->b , a->c , b->c 这样也完成游戏的任务。
假设a柱上有三个盘子,那我们应当将最小的盘子从a柱移到c柱,再将较小的盘子从a柱移到b柱,再将最小的盘子从c柱移到b柱,再将最大的盘子从a柱移到c柱,再将b柱最小的柱子移到a柱,再将b柱较小的盘子移到c柱,最后把a柱的盘子移到c柱。即 a->c , a->b , c->b , a->c , b->a , b->c , a->c 。
下面是代码实现。
#include<stdio.h>
void move (char pos1,char pos2)
{
printf(" %c->%c ",pos1,pos2);
}
void Hanoi (int n ,char pos1,char pos2,char pos3)
{
if(n==1)
{
move(pos1,pos3);
}
else
{
Hanoi(n-1,pos1,pos3,pos2);
move(pos1,pos3);
Hanoi(n-1,pos2,pos1,pos3);
}
}
int main ()
{
Hanoi(1,'a','b','c');
printf("\n");
Hanoi(2,'a','b','c');
printf("\n");
Hanoi(3,'a','b','c');
printf("\n");
}
运行结果如下:
如果觉得写的可以,关注点一点,下期更精彩。
边栏推荐
- No qualifying bean of type 问题
- 微软 AI 量化投资平台 Qlib 体验
- Detailed explanation of TCP (1)
- Detailed explanation of TCP (2)
- web容器及IIS --- 中间件渗透方法1
- type_traits metaprogramming library learning
- 端口排查步骤-7680端口分析-Dosvc服务
- [C language] General method of expression evaluation
- 问题7:列表的拼接
- SIP Protocol Standard and Implementation Mechanism
猜你喜欢

LocalDate加减操作及比较大小
![[C language] Preprocessing operation](/img/69/0aef065ae4061edaf0d96b89846bf2.png)
[C language] Preprocessing operation

C语言从入门到如土——数据的存储

Port inspection steps - 7680 port analysis - Dosvc service

qlib架构

立足本土,链接全球 | 施耐德电气“工业SI同盟”携手伙伴共赴未来工业
![[Paper reading] Mastering the game of Go with deep neural networks and tree search](/img/4f/899da202e13bd561bbfdbaeebe4d2e.jpg)
[Paper reading] Mastering the game of Go with deep neural networks and tree search

A brief introduction to the CheckBox component of the basic components of Flutter

Know the showTimePicker method of the basic components of Flutter

Postgresql 15 source code analysis (5) - pg_control
随机推荐
Golang中的addressable
(tree) Last Common Ancestor (LCA)
$parent/$children 与 ref
Regarding the primary key id in the mysql8.0 database, when the id is inserted using replace to be 0, the actual id is automatically incremented after insertion, resulting in the solution to the repea
[C language] Preprocessing operation
Detailed explanation of TCP and UDP
LocalDate addition and subtraction operations and comparison size
Redis uses LIST to cache the latest comments
Can‘t load /home/Iot/.rnd into RNG
Implementation of a sequence table
【论文阅读】Mastering the game of Go with deep neural networks and tree search
Zotero如何删除自动生成的标签
Redis 统计用户新增和留存
已解决:不小心卸载pip后(手动安装pip的两种方式)
Key Technologies of Interface Testing
[CV project debugging] CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT problem
Detailed explanation of TCP (2)
Pytest e-commerce project combat (on)
Automation strategies for legacy systems
RESTful api interface design specification


