汉诺塔-python递归

汉诺塔-Python代码实现(递归)

python 复制代码
def hannoi(n: int, x: str, y: str, z: str):
    """ 汉诺塔 """
    if n == 1:  # 一块圆盘,直接移动到Z
        print(x, ' -> ', z)
    else:
        # 不为一块圆盘,先将n-1个圆盘,从X通过Z,移动到Y
        hannoi(n - 1, x, z, y)
        print(x, ' -> ', z)     # X上只剩一块,然后移动到Z
        hannoi(n - 1, y, x, z)  # 再将n-1块圆盘,从Y通过X移动到Z


if __name__ == '__main__':
    hannoi(4, 'X', 'Y', 'Z')

# X  ->  Y
# X  ->  Z
# Y  ->  Z
# X  ->  Y
# Z  ->  X
# Z  ->  Y
# X  ->  Y
# X  ->  Z
# Y  ->  Z
# Y  ->  X
# Z  ->  X
# Y  ->  Z
# X  ->  Y
# X  ->  Z
# Y  ->  Z

小破站讲解视频:汉诺塔实现讲解

相关推荐
淘气的小猴子6 小时前
Python 魔术方法入门
python
我要见SA姐17 小时前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
ide·vscode·python·自动化·编辑器
沉下心来学鲁班7 小时前
初识DeepAgents搭建第一个智能体
人工智能·python·langchain
ctlover8 小时前
数据结构:树
数据结构·python
触底反弹9 小时前
🐍 Python 语法全景图:一个 print() 引发的深度探索
python
元Y亨H9 小时前
告别依赖地狱与打包崩溃:Python 项目环境治理与 PyInstaller 避坑实践
python
aramae9 小时前
Python 使用库:标准库与第三方库实战
服务器·开发语言·windows·python
IamZJT_9 小时前
Agent 系统工程 01|模型之外,Harness 到底该负责什么?
人工智能·python·程序员
沧海一笑-dj9 小时前
【Python】Python学习笔记-Python 核心基础
人工智能·python·ai·解释型语言
用户76855341255389 小时前
Python 并发怎么选?一篇讲清 threading、multiprocessing、asyncio 的边界
python