Chen Yin-ChenCYCU Biz Design
Home
About
AboutSchedule
Courses
Computational Thinking & ProgrammingNatural Science & Artificial IntelligenceProgramming Language Introduction
Interactive
Variable SwapMonty HallBetting SimulatorSliding PuzzleTower of Hanoi
Programming
JS Basic TutorialJavaScriptP5.js (Lecture)
Applications
Human Motion SystemAstrology SystemArchitecture System

Language

Traditional ChineseSimplified ChineseEnglish

Chen Yin-Chen

Business Design Department, Chung Yuan Christian University
Zishen Technology

Quick Links

  • About
  • Schedule
  • Games
  • JavaScript

Contact & Social

© 2026 Chen Yin-Chen。All rights reserved。

Built with Next.js & Tailwind CSS

🎮 Play🏆 Leaderboard📖 Theory

遞迴思維:用河內塔理解函數呼叫自身

遞迴(Recursion)是函數呼叫自身的程式設計技巧

什麼是遞迴?

一個合法的遞迴必須包含三個要素:

  • 基礎情況(Base Case):何時停止遞迴
  • 遞迴呼叫(Recursive Call):以更小的問題呼叫自身
  • 問題縮小(Reduction):確保每次呼叫都趨近基礎情況

河內塔的遞迴思路(分三步)

  1. 把上面的 n-1 個盤,從 A 移到 B(用 C 當中繼)
  2. 把最大的盤從 A 直接移到 C
  3. 把那 n-1 個盤,從 B 移到 C(用 A 當中繼)

Python 程式碼

def hanoi(n, from_rod, to_rod, via_rod):
    if n == 1:                          # 基礎情況
        print(f"移動圓盤 1:{from_rod} → {to_rod}")
        return

    hanoi(n - 1, from_rod, via_rod, to_rod)   # 步驟 1
    print(f"移動圓盤 {n}:{from_rod} → {to_rod}")  # 步驟 2
    hanoi(n - 1, via_rod, to_rod, from_rod)   # 步驟 3

hanoi(3, 'A', 'C', 'B')
# 移動圓盤 1:A → C    (共 7 步)
# 移動圓盤 2:A → B
# 移動圓盤 1:C → B
# 移動圓盤 3:A → C
# 移動圓盤 1:B → A
# 移動圓盤 2:B → C
# 移動圓盤 1:A → C

時間複雜度:最少步數 = 2ⁿ − 1

圓盤數最少步數備註
37可手動完成
101,023
201,048,575
6418,446,744,073,709,551,615♾️ 約 5800 億年(傳說世界末日)

在上方遊戲中,每完成一次移動就對應遞迴樹的一個「葉節點」。觀察步數是否符合 2ⁿ − 1 的規律!