CTCI 3.4

In the classic problem of the Towers of Hanoi, you have 3 towers and Ndisks of different sizes which can slide onto any tower.The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
(1) Only one disk can be moved at a time.
(2) A disk is slid off the top of one tower onto the next tower.
(3) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first tower to the last using stacks.

Use recursion to implement the algorithm. Assume we are move from a to c, with an additional b tower. If there is only one plate, directly move it from a to c, else, we first move the n-1, which n is the total plates on a from a to b using c as buffer, then move the last nth plate from a to c, then move the rest n-1 plates from b to c using a as buffer. In my implement, I use a inner class "Tower". However, when instantiation a Tower var in a static call, we need to first instantiation the outer class!

/* Using the recursion to implement the algorithm
*/
import java.util.*;

public class Hanoi {
    public void recursehanoi(int n, Tower a, Tower b, Tower c) {
        if(n == 1) { 
            System.out.println("Move the " + a.peek() + "th plate from " + a.name + " to " + c.name);
            c.add(a.remove()); 
        }
        else {
            //Move the top n-1 plates from a to b using c as buffer
            recursehanoi(n-1, a, c, b);
            //Move the last n from a to c
            System.out.println("Move the " + a.peek() + "th plate from " + a.name + " to " + c.name);
            c.add(a.remove()); 
            //Move the rest n-1 plates from b to c using a as buffer
            recursehanoi(n-1, b, a, c);
        }
    }

    public class Tower {
        public String name;
        public Stack<Integer> plates = new Stack<Integer>();
        public Tower(String name) {
            this.name = name;
        }

        public void add(int plate) {
            plates.push(plate);
        }

        public int peek() {
            return plates.peek();
        }

        public int remove() {
            return plates.pop();
        }
    }

    public static void main(String[] args) {
        Hanoi ha = new Hanoi();
        Hanoi.Tower a = new Hanoi().new Tower("a"); a.add(3); a.add(2); a.add(1);
        Hanoi.Tower b = new Hanoi().new Tower("b"); Hanoi.Tower c = new Hanoi().new Tower("c");
        ha.recursehanoi(3, a, b, c);
    }
}

 

转载于:https://www.cnblogs.com/pyemma/p/3834492.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值