共計 624 個字符,預計需要花費 2 分鐘才能閱讀完成。
下面是一個 Python 的漢諾塔問題的遞歸解決方案的代碼示例:
def hanoi(n, source, target, auxiliary):
if n > 0:
# 將 n-1 個盤子從源柱移動到輔助柱
hanoi(n-1, source, auxiliary, target)
# 將最底下的盤子從源柱移動到目標柱
print(f"Move disk {n} from {source} to {target}")
# 將 n-1 個盤子從輔助柱移動到目標柱
hanoi(n-1, auxiliary, target, source)
# 測試
hanoi(3, 'A', 'C', 'B')
這段代碼中,hanoi函數接受四個參數:整數 n 表示盤子的數量,字符串 source 表示源柱,字符串 target 表示目標柱,字符串 auxiliary 表示輔助柱。函數使用遞歸的方式解決漢諾塔問題。
在 hanoi 函數中,首先檢查 n 是否大于 0。如果是,則遞歸調用函數本身:
- 第一次遞歸調用將前 n-1 個盤子從源柱移動到輔助柱 (
source到auxiliary)。 - 打印移動最底下的盤子從源柱移動到目標柱 (
source到target)的操作。 - 第二次遞歸調用將前 n-1 個盤子從輔助柱移動到目標柱 (
auxiliary到target)。
最后,我們調用 hanoi 函數來測試代碼,并將 source 設置為 "A",target設置為 "C",auxiliary設置為 "B"。
丸趣 TV 網 – 提供最優質的資源集合!
正文完