河內(nèi)塔中的每個(gè)堆棧如何問(wèn)題如何逐行執(zhí)行我不太明白每個(gè)堆棧的創(chuàng)建方式???public class TowerOfHanoi { public static void towerOfHanoi(int disks, char source, char auxiliary, char destination) { if (disks == 0) { return; } towerOfHanoi(disks - 1, source, destination, auxiliary); System.out.println(source + " " + destination); towerOfHanoi(disks - 1, auxiliary, source, destination); } public static void main(String[] args) { towerOfHanoi(4, 'a', 'b', 'c'); }}
1 回答

DIEA
TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超2個(gè)贊
這個(gè)應(yīng)該工作:
private static void hanoiTower(int n, char from_rod, char to_rod, char aux_rod){
if(n == 1){
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
hanoiTower(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
hanoiTower(n-1, aux_rod, to_rod, from_rod);
}
添加回答
舉報(bào)
0/150
提交
取消