複製代碼代碼如下:
package com.tiantian.algorithms;
/**
* _|_1 | |
* __|__2 | |
* ___|___3 | | (1).把A上的4個木塊移動到C上。
* ____|____4 | |
* ABC
*
* | | |
* | _|_1 |
* | __|__2 | 要完成(1)的效果,必須要把1、2、3木塊移動到B,這樣才能把4移動到C
* ____|____4 ___|___3 | 如:代碼中的“調用(XX)”
* ABC
*
* | | |
* | _|_1 |
* | __|__2 | 此時,題目就變成了把B上的3個木塊移動到C上,回到了題目(1)
* | ___|___3 ____|____4 如:代碼中的“調用(YY)”
* ABC
*
* 然後循環這個過程
*
* @author wangjie
* @version 創建時間:2013-3-4 下午4:09:53
*/
public class HanoiTowerTest {
public static void main(String[] args) {
doTowers(4, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to){
if(topN == 1){
System.out.println("最後把木塊1從" + from + "移動到" + to);
}else{
doTowers(topN - 1, from, to, inter); // 調用(XX)
System.out.println("把木塊" + topN + "從" + from + "移動到" + to);
doTowers(topN - 1, inter, from ,to); // 調用(YY)
}
}
}