Java實現漢諾塔移動,只需傳一個int值(漢諾塔的階)

 1 public class HNT {
 2     public static void main(String[] args) {
 3         HNT a1 = new HNT();
 4         a1.lToR(10);    //給漢諾塔a1左邊放10階的層數,把左邊的10階移動至右邊。
 5     }
 6     private boolean pHToM(int num,String a,String b,String c) {        //打印移動數據,從a移動到c.
 7         if (num == 1) {        //只移動一層的狀況,return false表示,若是num == 1則再也不繼續打印num<1的狀況
 8             System.out.printf("%s to %s\n",a,c);
 9             return false;
10         }
11         else if (num == 2) {    //只移動兩層的狀況,return false表示,若是num == 2則再也不繼續打印num<2的狀況
12             System.out.printf("%s to %s\n",a,b);
13             System.out.printf("%s to %s\n",a,c);
14             System.out.printf("%s to %s\n",b,c);
15             return false;
16         }
17         else {        //
18             return true;    //移動大於兩層的狀況,return true表示,若是num>2則繼續循環到num<=2爲止
19         }
20     }
21     public void lToR(int num) {        //把num層的漢諾塔從左移動至右
22         if(pHToM(num,"left","mid","right")) {
23             lToM(num - 1);
24             lToR(1);
25             mToR(num - 1);
26         }
27     }
28     public void lToM(int num) {        //把num層的漢諾塔從左移動至中
29         if(pHToM(num,"left","right","mid")) {
30             lToR(num - 1);
31             lToM(1);
32             rToM(num - 1);
33         }
34     }
35     public void mToL(int num) {        //把num層的漢諾塔從中移動至左
36         if(pHToM(num,"mid","right","left")) {
37             mToR(num - 1);
38             mToL(1);
39             rToL(num - 1);
40         }
41     }
42     public void mToR(int num) {        //把num層的漢諾塔從中移動至右
43         if(pHToM(num,"mid","left","right")) {
44             mToL(num - 1);
45             mToR(1);
46             lToR(num - 1);
47         }
48     }
49     public void rToL(int num) {        //把num層的漢諾塔從右移動至左
50         if(pHToM(num,"right","mid","left")) {
51             rToM(num - 1);
52             rToL(1);
53             mToL(num - 1);
54         }
55     }
56     public void rToM(int num) {        //把num層的漢諾塔從右移動至中
57         if(pHToM(num,"right","left","mid")){
58             rToL(num - 1);
59             rToM(1);
60             lToM(num - 1);
61         }
62     }
63 }
相關文章
相關標籤/搜索