我正在努力提高我对python中hanoi之塔递归解决方案代码的理解。
此代码: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")
将打印出解决这个难题所需的正确步骤,因此我在前一段时间询问了堆栈溢出问题,以了解它是如何做到这一点的。我得到了这个答案
^{pr2}$
关于这个解释,我唯一不明白的是,在递归中,磁盘目标(peg a、b、c)是如何变化的?第三行-移动塔:1a B,是正确的,我知道光盘应该从A移动到B,但我不明白我们是如何从A到C(第二行)到新的目的地B!这很难解释,如果你不明白我的意思,请问我,但我真的很想帮助你理解这一点!
这就是我所理解的代码,对于3张盘,从=A到=B,with=C,我写了我认为递归应该是什么样子的(这忽略了大部分代码,我只关注顶部部分def moveTower(3,A, B, C):
if height >= 1:
moveTower(2,A,C,B)
moveTower(1,A, C, B) #so this line of code should be A,B,C but why? as in recursion do we not simply repeat the code again and again? so why would it change if the code initially is ACB why does it change to ABC?
moveDisk(A,B,3)
moveTower(1,C,B,A)