python递归解决汉诺塔问题

本文通过Python代码展示了如何解决经典的汉诺塔问题。代码中定义了递归函数moveTower来移动不同高度的盘子,并使用辅助柱完成从A柱到C柱的移动过程。通过观察输出结果可以清晰地看到每一步移动的具体操作。
摘要由CSDN通过智能技术生成

兄弟萌,话不多说,show me the code!

def moveTower(height,fromPole,withPole,toPole):
    if height >= 1:
        moveTower(height-1,fromPole,toPole,withPole)
        moveDisk(height,fromPole,toPole)
        moveTower(height-1,withPole,fromPole,toPole)

def moveDisk(disk,fromPolem,toPole):
    print(f"Moving disk [{disk}] from {fromPolem} to {toPole}")


if __name__ == '__main__':
    moveTower(5,"a","b","c")

输出:

Moving disk [1] from a to c
Moving disk [2] from a to b
Moving disk [1] from c to b
Moving disk [3] from a to c
Moving disk [1] from b to a
Moving disk [2] from b to c
Moving disk [1] from a to c
Moving disk [4] from a to b
Moving disk [1] from c to b
Moving disk [2] from c to a
Moving disk [1] from b to a
Moving disk [3] from c to b
Moving disk [1] from a to c
Moving disk [2] from a to b
Moving disk [1] from c to b
Moving disk [5] from a to c
Moving disk [1] from b to a
Moving disk [2] from b to c
Moving disk [1] from a to c
Moving disk [3] from b to a
Moving disk [1] from c to b
Moving disk [2] from c to a
Moving disk [1] from b to a
Moving disk [4] from b to c
Moving disk [1] from a to c
Moving disk [2] from a to b
Moving disk [1] from c to b
Moving disk [3] from a to c
Moving disk [1] from b to a
Moving disk [2] from b to c
Moving disk [1] from a to c

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值