首先,你的代码并不完全正确。这里是改变的towers
功能 - >
def towers (n, fr, to, sp):
if n == 1:
printMove (to, fr)
else:
towers (n-1, fr, sp, to)
printMove (to,fr)
towers (n-1, sp, to, fr)
这里去解释。看图片 - >
通过调用Movetower(3,a,b,c)
,你打算将所有从塔A
3盘至塔B
。因此,连续通话是 - >
1. Movetower(3,a,b,c) // No Move needed
2. Movetower(2,a,c,b) // No move needed
3. Movetower(1,a,b,c) // Here is the time to move, move disc1 from a to b
4. Movetower(2,a,c,b) // Returning to this call again, this is the time to move disc2 from a to c
5. Movetower(1,b,c,a) // Again the time to move, this time disc1 from b to c
6. Movetower(3,a,b,c) // Returning to this call again, this is the time to move disc3 from a to b
7. Movetower(2,c,b,a) // Not the time to move
8. Movetower(1,c,a,b) // Here is the time to move, move disc1 from c to a
9. Movetower(2,c,b,a) // Returning to this call again, this is the time to move disc2 from c to b
10.Movetower(1,c,a,b) // Here is the time to move, move disc1 from a to b
希望它能帮助:)
您还可以找到一些很好的解释在这里:Tower of Hanoi: Recursive Algorithm
动画:https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html
感谢您的解释,我使用的代码是从edx MIT介绍到使用python进行计算和编程。我试图重新创建它,但没有逐字拷贝,并意识到我无法得到正确的顺序,并且不理解每一步。 – neoraiden
不客气!很高兴知道它帮助:) – jbsu32