python递归汉诺塔详解_汉诺塔在python中递归,理解磁盘目的地的变化
我正在努力提高我對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)
總結
以上是生活随笔為你收集整理的python递归汉诺塔详解_汉诺塔在python中递归,理解磁盘目的地的变化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot 优雅的参数校验_S
- 下一篇: verilog 浮点转定点_定点数优化: