/*** Function: Hanoi tower problem* Description: There are 3 pillars and n different sizes of perforated discs, the plate can slide into any one pillar. At first,* All plates are placed from the bottom up to the top of the first pillar (i.e. each plate can only be put on a larger plate). * The following restrictions apply when moving a disc:* 1) only one plate can be moved at a time. * 2) the plate can only slide out from the top of the pillar to move to the next pillar. * 3) The plate can only be stacked on a plate bigger than it. * Please use the stack to move all the plates from the first pillar to the last pillar. */
Import Java.util.stack;public class Demo {public static void main (string[] args) {//TODO auto-generate d method stub int n=3; int disks=5; Tower[] towers= new tower[n]; for (int i=0; i< n; i++) {towers[i]= new Tower (i); } for (int i= disks; i>=0; i--) {towers[0].add (i); } towers[0].movedisks (disks, towers[2], towers[1]); }}class tower{public stack<integer> disks; public int index; public Tower (int index) {disks= new stack<integer> (); This. index= index; } public int GetIndex () {return this. index; } public void Add (int d) {if (! Disks.isempty () && Disks.peek () <= D) syst Em. Out.println ("Error placing Disk" +d); else Disks.push (d); } Move the plate at the top of the orgin to the destination public void Movetotop (Tower t) {int top= disks.pop (); T.add (top); System. OUT.PRINTLN ("Move disk" + top+ "from" +this.getindex () + "to" +t.getindex ()); } public void Movedisks (int n,tower destination,tower buffer) {if (n>0) {//Will top End N-1 Plate moved from origin to buffer movedisks (n-1, buffer, destination); This.movetotop (destination); Move the top n-1 plate from buffer to destination, using origin as a buffer buffer.movedisks (n-1, destination, this); } }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.3 Stacks and Queues (v)--Hanoi tower problem