汉诺塔-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

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

相关推荐
GDAL1 小时前
uv 完整教程:下一代 Python 包管理工具
python·uv
曲幽8 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
装不满的克莱因瓶9 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..9 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
金銀銅鐵9 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf9 小时前
Python 模块与包的导入导出
前端·后端·python
ice81303318110 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
copyer_xyf10 小时前
Python venv 虚拟环境
前端·后端·python
林爷万福11 小时前
GitHub 开源光谱数据处理项目推荐
python·光纤光谱仪
copyer_xyf11 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python