用递归方法写出3阶汉诺塔的操作

解决方案 »

  1.   

    简单的一个,手写的,没编译,测试。public class Hanoi
    {
       public static void main(String[] args)
       {
          action(3, 'A', 'B', 'C');
       }   //把n个盘子从a移到c,通过b
       public static void action(int n, char a, char b, char c)
       {
            if (1 == n)
            {
               System.out.println("move Dish No.:" + n + " from " + a + " to " + c);
            } else
            {
               action(n-1, a, c, b);
               System.out.println("move Dish No.:" + n + " from " + a + " to " + c);
               action(n-1, b, a, c);
            }
       }
    }也没考虑堆栈溢出。
    不过希望有人把这个用迭代算法实现的思想或者代码(带注释)贴出来看看。
    见笑了。
      

  2.   

    /**
     * The Tower of Hanoi (sometimes referred to as the Tower of Brahma or the End
     * of the World Puzzle) was invented by the French mathematician, Edouard Lucas,
     * in 1883. He was inspired by a legend that tells of a Hindu temple where the
     * pyramid puzzle might have been used for the mental discipline of young
     * priests. Legend says that at the beginning of time the priests in the temple
     * were given a stack of 64 gold disks, each one a little smaller than the one
     * beneath it. Their assignment was to transfer the 64 disks from one of the
     * three poles to another, with one important provisoøa large disk could never
     * be placed on top of a smaller one. The priests worked very efficiently, day
     * and night. When they finished their work, the myth said, the temple would
     * crumble into dust and the world would vanish.
     * 
     * @author protozz
     * 
     */
    public class TowerOfHanoi { public void move(int disks, char a, char b, char c) {
    if (disks > 0) {
    move(disks - 1, a, c, b);
    System.out.println("Move " + a + " to " + c);
    move(disks - 1, b, a, c);
    }
    }
    public static void main(String[] args) {
    TowerOfHanoi  t = new TowerOfHanoi();
    t.move(3,'a','b','c');
    }
    }