2013-02-01 51 views
1

我知道河內塔背後的想法,知道算法,但我在實施它時遇到了麻煩。遞歸解答河內塔

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) 

我遇到的問題是我不知道如何將遞歸定義與類函數結合來移動磁盤。

+1

這是一個語法問題?我不確定我是否遵守。 – BlackVegetable

+0

def hanoi是一種遞歸的語法,但我需要將它添加到某處h.move(src,spare)等,但我遇到了麻煩如何做 –

+0

有一個[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

回答

1

你需要把遞歸調用的move()spare()體內並移動功能hanoi()的邏輯到相關方法

所以

class Hanoi(object): 

    # snip 

    def move(self, src, dst): 

     # your logic goes here 
     # example of a recursive call 
     self.move(foo, bar) 
+0

有沒有辦法在河內函數中做到這一點,我想離開這個類,並把它遞歸到河內函數中 –

+0

你不需要創建一個類,只需直接編寫你的函數。您是否在Java中使用帶有示例的教科書? – YXD