python - Towers of Hanoi Python——理解递归

标签 python algorithm recursion towers-of-hanoi

<分区>

我是 Python 的新手,目前正在学习有关汉诺塔和递归的教程。在他们给出这个例子之前,我认为我理解递归:

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

def moveDisk(fp,tp):
    print("moving disk from",fp,"to",tp)


moveTower(3,"A","B","C")

它打印出用 3 个圆盘解决汉诺塔问题的正确步骤: 将磁盘从 A 移动到 B 将磁盘从 A 移动到 C 将磁盘从 B 移动到 C 将磁盘从 A 移动到 B 将磁盘从 C 移动到 A 将磁盘从 C 移动到 B 将磁盘从 A 移动到 B

我的问题是,它是怎么做到的?!有人可以检查代码行以便我了解它如何打印正确的 Action 吗?我主要对 fptp 的值如何从 ABC。对不起,如果这是一个广泛的问题!任何帮助将不胜感激!

最佳答案

在这个简单的例子中,您可以通过使用适当的 print 来想象发生了什么,就像这样:

def moveTower(height,fromPole, toPole, withPole):
    if height >= 1:
        print( "    "*(3-height), "moveTower:", height, fromPole, toPole )
        moveTower(height-1,fromPole,withPole,toPole)
        moveDisk(fromPole,toPole,height)
        moveTower(height-1,withPole,toPole,fromPole)
    #print(withPole)

def moveDisk(fp,tp,height):
    print("    "*(4-height), "moving disk", "~"*(height), "from",fp,"to",tp)


moveTower(3,"A","B","C")

输出是:

moveTower: 3 A B
     moveTower: 2 A C
         moveTower: 1 A B
             moving disk ~ from A to B
         moving disk ~~ from A to C
         moveTower: 1 B C
             moving disk ~ from B to C
     moving disk ~~~ from A to B
     moveTower: 2 C B
         moveTower: 1 C A
             moving disk ~ from C to A
         moving disk ~~ from C to B
         moveTower: 1 A B
             moving disk ~ from A to B

关于python - Towers of Hanoi Python——理解递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23107610/

相关文章:

python - Databricks:spark 数据框中的 Python 数据透视表

javascript - 从迷宫中找到最短路径(广度优先搜索)

c - 使用 XCB 的奇怪递归行为

python - PyMySQL 将(文件)数据加载到远程 MySQL 实例时出现错误/异常

python - 将 paver 和 nose 与非典型目录结构一起使用

python - 使用 pandas/python 字典绘制二维数组

algorithm - 在 WebGL 中使用 for 循环进行二进制搜索

javascript - 是否可以枚举计算机程序?

c - C递归检查回文

haskell - 递归还是列表理解?