//2009年8月22日中午12点10分(周六)完成于紫金港某教室。 public class HanNuoTa { int laotai = 0;//移动次数 /**递归方法*/ public void go(int num,String x,String y){ if(num==0){ return; }else{ String z = getZ(x,y); go(num-1,x,z); System.out.println("将"+num+"号盘从"+x+"移到"+y); laotai++; go(num-1,z,y); } } /**得到中转的柱子*/ public String getZ(String x,String y){ if(!"C柱".equals(x)&&!"C柱".equals(y)){ return "C柱"; } if(!"B柱".equals(x)&&!"B柱".equals(y)){ return "B柱"; } return "A柱"; } /**主方法,程序入口*/ public static void main(String[] args) { int num = 10; //盘子数目 String x = "A柱"; //盘子所在的柱子 String y = "B柱"; //盘子要移往的柱子 HanNuoTa shanxi = new HanNuoTa(); shanxi.go(num,x,y); System.out.print("将"+num+"个盘子从"+x+"移动到"+y+","); System.out.println("一共要移动"+shanxi.laotai+"次."); } //写代码的最高境界:多一行则胖,少一行则瘦。 //如果要把10个盘子从A移到B,先要把上面的9个盘子从A移到C,然后把第十个盘子从A移到B,再接着把前9个盘子从C移到B。 //由此可以看出,转移n个盘子所需的次数 = 转移n-1个盘子的次数 * 2 + 1 。 //就跟那个国际象棋上放大米的故事一样。如果盘子数很大,那移动次数是惊人的。 //将10个盘子从A柱移动到B柱,一共要移动1023次. //将15个盘子从A柱移动到B柱,一共要移动32767次. //看看这增长速度,可想而知,要移动100个盘子,那移动的次数该有多么恐怖了。 }