在Java中,如何使用方法來解決漢諾塔的問題?
本範例顯示了解決漢諾塔問題的方法(3個盤)。
package com.yiibai;
public class TowerOfHanoi {
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to) {
if (topN == 1) {
System.out.println("Disk 1 from " + from + " to " + to);
} else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
執行上面範例程式碼,得到以下結果 -
Disk 1 from A to C
Disk 2 from A to B
Disk 1 from C to B
Disk 3 from A to C
Disk 1 from B to A
Disk 2 from B to C
Disk 1 from A to C
範例-2
以下是解決漢諾塔的另一個例子
package com.yiibai;
public class TowerOfHanoi2 {
public static void move(int n, int startPole, int endPole) {
if (n == 0) {
return;
}
int intermediatePole = 6 - startPole - endPole;
move(n - 1, startPole, intermediatePole);
System.out.println("Move " + n + " from " + startPole + " to "
+ endPole);
move(n - 1, intermediatePole, endPole);
}
public static void main(String[] args) {
move(5, 1, 3);
}
}
執行上面範例程式碼,得到以下結果 -
Move 1 from 1 to 3
Move 2 from 1 to 2
Move 1 from 3 to 2
Move 3 from 1 to 3
Move 1 from 2 to 1
Move 2 from 2 to 3
Move 1 from 1 to 3
Move 4 from 1 to 2
Move 1 from 3 to 2
Move 2 from 3 to 1
Move 1 from 2 to 1
Move 3 from 3 to 2
Move 1 from 1 to 3
Move 2 from 1 to 2
Move 1 from 3 to 2
Move 5 from 1 to 3
Move 1 from 2 to 1
Move 2 from 2 to 3
Move 1 from 1 to 3
Move 3 from 2 to 1
Move 1 from 3 to 2
Move 2 from 3 to 1
Move 1 from 2 to 1
Move 4 from 2 to 3
Move 1 from 1 to 3
Move 2 from 1 to 2
Move 1 from 3 to 2
Move 3 from 1 to 3
Move 1 from 2 to 1
Move 2 from 2 to 3
Move 1 from 1 to 3