漢諾塔問題是一個經典的遞歸問題
public class HanoiTower {
private int source;
private int auxiliary;
private int target;
public HanoiTower(int source, int auxiliary, int target) {
this.source = source;
this.auxiliary = auxiliary;
this.target = target;
}
}
moveDisk
,該方法接受四個參數:漢諾塔對象、源柱子上的磁盤數量、輔助柱子和目標柱子。public void moveDisk(HanoiTower tower, int n, int from, int to, int via) {
if (n == 1) {
System.out.println("Move disk 1 from " + from + " to " + to);
} else {
moveDisk(tower, n - 1, from, via, to);
System.out.println("Move disk " + n + " from " + from + " to " + to);
moveDisk(tower, n - 1, via, to, from);
}
}
moveDisk
方法來解決問題。public class Main {
public static void main(String[] args) {
HanoiTower tower = new HanoiTower(1, 2, 3);
moveDisk(tower, 3, 1, 3, 2);
}
}
運行上述代碼,你將看到解決3個磁盤漢諾塔問題的詳細步驟。你可以通過更改moveDisk
方法的第一個參數來改變磁盤的數量。