首页 > 代码库 > CTCI 3.4
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); }}