当前位置: 首页 > backend >正文

C语言编程--递归程序--Hanoi塔

任务:
We have 3 3 3 pegs and N N N disks that fit onto the pegs. The disks differ in size, and are initially arranged on one of the pegs, in order from largest (disk N N N) at the bottom to smallest (disk 1 1 1) at the top.
The task is to move the stack of disks to the right one position (peg), while obeying the following rules:

  • only one disk may be shifted at a time, and
  • no disk may be placed on top of a smaller one.

实现:

#include <stdio.h>void hanoi(int N, int d);
void shift(int N, int d);int main(){// 测试3个盘子printf("Testing 3 pegs start...\n");hanoi(3,1);printf("Testing 3 pegs end....\n");//测试5个盘子printf("Testing 5 pegs start...\n");hanoi(5,1);printf("Testing 5 pegs end...\n");return 0;
}void hanoi(int N, int d){if (N == 0) {return ;}//先把N-1个盘子向左移动hanoi(N-1, -d);//再把第N个盘子向右移动shift(N, d);//最后把N-1个盘子向左移动到第N个盘子上hanoi(N-1, -d);
}void shift(int N, int d){if (d > 0) {printf("shift(%d, +%d)\n", N,d);}else {printf("shift(%d, %d)\n", N,d);}}

递归调用图
递归调用图
递归调用树
递归调用树

  • 对应图5.7左下侧的hanoi(3,+1)的递归调用图
  • 采用后续遍历的方式即可得到hanoi(3,+1)的递归调用返回序列
http://www.xdnf.cn/news/4462.html

相关文章:

  • 企业智能化第一步:用「Deepseek+自动化」打造企业资源管理的智能中枢
  • MEGA3:分子进化遗传学分析和序列比对集成软件
  • 检测内存条好坏有工具,推荐几款内存检测工具
  • github+ Picgo+typora
  • OpenCV提取图像中的暗斑/亮斑
  • IvorySQL 再次走进北京大学研究生开源公选课
  • onenet连接微信小程序(mqtt协议)
  • 【国产化】在银河麒麟ARM环境下离线安装docker
  • Spring 如何解决循环依赖问题?
  • JavaScript性能优化:从青铜到王者的进阶之路
  • 从人体姿态到机械臂轨迹:基于深度学习的Kinova远程操控系统架构解析
  • Kubernetes(k8s)学习笔记(九)--搭建多租户系统
  • QMK键盘固件配置详解
  • 2025.05.07-华为机考第三题300分
  • DIFY教程第四弹:通过工作流来创建一个SQL语句的执行器
  • 【计算机基础】任意进制转换方法详解
  • 资产管理系统对比评测:从传统模式到 AI 驱动的变革
  • 引用的使用
  • [Es_1] 介绍 | 特点 | 图算法 | Trie | FST
  • 【C/C++】errno/strerror 和 GetLastError()/FormatMessage 的区别
  • 模拟设计中如何减小失配
  • 4.系统定时器基本定时器
  • 操作系统——第四章(文件的物理结构以及与逻辑结构的对比)
  • Redis相关命令详解与原理
  • 【Agent】使用 Python 结合 OpenAI 的 API 实现一个支持 Function Call 的程序,修改本机的 txt 文件
  • 如何检查 Watchtower 是否正常工作及更新未生效的排查方法【日常排错】
  • 探寻程序开发的个人密码
  • excel 批量导出图片并指定命名
  • Excel点击单元格内容消失
  • 龙虎榜——20250507