我知道河內塔背後的想法,知道算法,但我在實施它時遇到了麻煩。遞歸解答河內塔
class Hanoi:
def __init__(self, n):
== code==
def move(self, src, dst):
=code for moving the disk from source to destination==
def spare(self, src, dst):
==Returns the peg which is not src and dst==
def print_pegs(self):
h = Hanoi(4)
def hanoi(n, src, dst):
if n==1:
h.move(src,dst)
else:
spare=h.spare(src,dst)
hanoi(n-1,src,spare)
hanoi(1,src,dst)
hanoi(n-1,spare,dst)
hanoi(4, 0, 2)
我遇到的問題是我不知道如何將遞歸定義與類函數結合來移動磁盤。
這是一個語法問題?我不確定我是否遵守。 – BlackVegetable
def hanoi是一種遞歸的語法,但我需要將它添加到某處h.move(src,spare)等,但我遇到了麻煩如何做 –
有一個[MIT講座](http:// ocw。 mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/unit-1/lecture-6-recursion/)處理問題。 – root