数据结构--汉诺塔递归Java实现

 1 /*汉诺塔递归
 2  * 1.将编号0-N-1个圆盘,从A塔座移动到B上面
 3  * 2.将编号N的1个圆盘,从A移动到C上面
 4  * 3.最后将B上面的N-1个圆盘移动到C上面
 5  * 注意:盘子的编号从上到下1-N
 6  * */
 7 public class HannoTower_Recursion {
 8 
 9     public static void main(String[] args) {
10         int nDisk = 3;
11         doTowers(nDisk,'A','B','C');
12 
13     }
14 
15     private static void doTowers(int topN, char from, char inter, char to) {
16         if(topN == 1){
17             //只有一个盘子编号为1,直接从A移动到C上面
18             System.out.println("Disk 1 " + "from " + from + " to " + to);
19         }
20         else{
21             //将前N-1个盘子从A移动到B---from-->inter
22             doTowers(topN-1, from, to, inter);
23             //将第N个盘子从A移动到C---from-->to
24             System.out.println("Disk " + topN  + "from " + from + " to " + to);
25             //将前N-1个盘子从B移动到C---inter-->to
26             doTowers(topN-1, inter, from,to );
27         }
28     }
29 
30 }

执行过程和结果

Enter(3 disks,A B C)

  Enter(2 disks,A,C,B)

    Enter(1disk,A B C)

    Base case-->disk1 from A---C   //Disk 1 from A to C

    Return(1disk A B C)

    move disk 2 from A--B    //Disk 2from A to B

    Enter(1disk, C,A,B)

    Base case-->disk1 from C---B   //Disk 1 from C to B

    Return(1disk C A B)

  Return(2disk A C B)

  move disk 3 from A--C    //Disk 3from A to C

  Enter(2disk B A C)

    Enter(1disk B C A)

    Base case-->disk1 from B---A   //Disk 1 from B to A

    Return(1disk B C A)

    move disk 2 from B--C    //Disk 2from B to C

    Enter(1disk A B C)

    Base case-->disk1 from A---C   //Disk 1 from A to C

    Return(1disk A B C)

  Return(2disk B A C)

Return(3 disks,A B C)

 

posted @ 2017-11-09 21:02  sun1993  阅读(618)  评论(0编辑  收藏  举报