遞迴之漢諾塔
阿新 • • 發佈:2021-10-24
原始碼
package 遞迴基礎小題; /** * @author 鄧雪松 (づ ̄ 3 ̄)づ) * @create 2021-10-24-21-02 */ public class 漢諾塔 { public static void main(String[] args) { printHonoiTower(3,"A","B","C"); } /** * * @param N 初始的N個從小到大的盤子,N是最大編號 * @param from 原始柱子 * @param to 目標的柱子 * @param help 輔助柱子 */ static void printHonoiTower(int N,String from,String to,String help){ if(N==1){ System.out.println("move "+N+" from "+from+" to "+to); return; } printHonoiTower(N-1,from,help,to);//先把前N-1個盤子挪到輔助空間上去 System.out.println("move "+N+" from "+from+" to "+to);//N可以順利到達target printHonoiTower(N-1,help,to,from);//讓N-1從輔助空間回到原空間上去 } }
執行結果
move 1 from A to B
move 2 from A to C
move 1 from B to C
move 3 from A to B
move 1 from C to A
move 2 from C to B
move 1 from A to B
如果不明白執行次序可以敲出來然後debug