汉诺塔问题是一个经典的递归问题
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
方法的第一个参数来改变磁盘的数量。