码迷,mamicode.com
首页 > 其他好文 > 详细

Hanoi

时间:2015-09-23 18:34:06      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

递归解决 汉诺塔

 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 }

 

Hanoi

标签:

原文地址:http://www.cnblogs.com/jack-xu/p/4832728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!