Towers Of Hanoi.
There are three pegs: A, B and C. There are n disks. All disks are different in size.
The disks are initially stacked on peg A so that they increase in size from the top to the bottom.
The goal is to transfer the entire tower from the A peg to the C peg.
One disk at a time can be moved from the top of a stack either to an empty peg or to
a peg with a larger disk than itself on the top of its stack.
The method should return a sequence of disk moves, each move is a String with two letters (A, B or C)
corresponding to the peg the disk moves from and the peg it moves to.
For example, the move "AC" means that a top disk from peg A should be moved to peg C.
*/
importjava.util.ArrayList;importjava.util.List;publicclassTowersOfHanoi {privatestaticList<String> list=newArrayList<String>();staticString a="A";staticString c="C";staticString b="B";staticString s="";publicstaticvoidmove(intn,intstartPole,intendPole) {if(n==0){return;}intintermediatePole =6- startPole - endPole;move(n-1, startPole, intermediatePole);System.out.println("Move "+n +" from "+ startPole +" to "+endPole);if(startPole==1)s=s+a;if(startPole==2)s=s+b;if(startPole==3)s=s+c;if(endPole==1)s=s+a;if(endPole==2)s=s+b;if(endPole==3)s=s+c;list.add(s);s="";move(n-1, intermediatePole, endPole);}publicstaticList<String> transferFromAtoC(intn) {/*Towers Of Hanoi.There are three pegs: A, B and C. There are n disks. All disks are different in size.The disks are initially stacked on peg A so that they increase in size from the top to the bottom.The goal is to transfer the entire tower from the A peg to the C peg.One disk at a time can be moved from the top of a stack either to an empty peg or toa peg with a larger disk than itself on the top of its stack.The method should return a sequence of disk moves, each move is a String with two letters (A, B or C)corresponding to the peg the disk moves from and the peg it moves to.For example, the move "AC" means that a top disk from peg A should be moved to peg C.*/move(n,1,3);returnlist;}publicstaticvoidmain(String[] args) {List l1 =newArrayList();transferFromAtoC(1);System.out.println(list);}- }
Download Link: Click Here

0 comments:
Post a Comment