河內塔
在這個練習中,你要用遞迴演算法實作河內塔謎題。這個遊戲的目標是把所有圓盤從三根柱子中的其中一根,依規則移到另一根:
- 每次只能移動一個圓盤。
- 你只能從某一疊的最上方取下圓盤,並放到另一疊的最上方。
- 不可把較大的圓盤放在較小的圓盤上。

下面的演算法是此遊戲在有 4 個圓盤與 3 根分別名為 'A'、'B'、'C' 的柱子時的實作。程式碼中有兩個錯誤。事實上,若你直接執行,它會因為超過最大遞迴深度而讓主控台當掉。你能找出錯誤並修好它們嗎?
本練習屬於課程
Data Structures and Algorithms in Python
練習說明
- 修正基底情況。
- 修正對
hanoi()的呼叫。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def hanoi(num_disks, from_rod, to_rod, aux_rod):
# Correct the base case
if num_disks >= 0:
# Correct the calls to the hanoi function
hanoi(num_disks, from_rod, aux_rod, to_rod)
print("Moving disk", num_disks, "from rod", from_rod,"to rod",to_rod)
hanoi(num_disks, aux_rod, to_rod, from_rod)
num_disks = 4
source_rod = 'A'
auxiliar_rod = 'B'
target_rod = 'C'
hanoi(num_disks, source_rod, target_rod, auxiliar_rod)