Hanoi

递归解决 汉诺塔

 1 class Han{
 2     int num;
 3     int steps;
 4     Han(int num){
 5         this.num=num;
 6     }
 7     void total()
 8     {
 9         System.out.println("total="+steps);
10     }
11     void show(int i, int from, int des, String[] str)
12     {
13         int tmp = 3-from-des;//0+1+2=3
14         if (i==2)
15         {
16             System.out.println(1+":"+str[from]+"->"+str[tmp]);
17             System.out.println(2+":"+str[from]+"->"+str[des]);
18             System.out.println(1+":"+str[tmp]+"->"+str[des]);            
19             steps+=3;
20         }else
21         {
22             show(i-1, from, tmp, str);
23             System.out.println(i+":"+str[from]+"->"+str[des]);
24             show(i-1, tmp, des, str);
25             steps+=1;
26         }
27     }
28 } 
29 
30 public class HelloWorld{
31     public static void main(String[] args) {
32         Han h=new Han(5);//set numbers of member
33         String[] str= {"A","B","C"};//three pillars
34         h.show(h.num, 0, 2, str);//from pillar 0 to pillar 2
35         h.total();//2^n-1
36     }
37 }

 

posted @ 2015-09-23 16:41  jack-xu  阅读(401)  评论(0编辑  收藏  举报