Write a recursive method that prints out the individual move

Write a recursive method that prints out the individual moves you need to perform to solve a Towers of Hanoi problem with n rings. while Using stacks to represent the pegs and integers to represent your disks, and “A,” “B,” and “C,” as labels for your pegs. Java netbeans

Solution

Hi, Please find my code.

Please let me know in case of any issue.

/**here is a stack of N disks on the first of three poles (call

them A, B and C) and your job is to move the disks from pole A to pole C without

ever putting a larger disk on top of a smaller disk.*/

public class TowersOfHanoi {

   public void move(int n, String start, String auxiliary, String end) {

      

       // base case

       if (n == 1) {

           // When n==1, it means we are left with only one disk, so directly move it from source to destination.

           System.out.println(start + \" -> \" + end);

       } else {

           // Move (n-1 disk) from Source Peg (A) to Auxiliary Peg (B)

           move(n - 1, start, end, auxiliary);

           //Move last nth disk to Destination Peg (C).

           System.out.println(start + \" -> \" + end);

           //Move (n-1 disk) from Auxiliary Peg(B) to Destination Peg(C).

           move(n - 1, auxiliary, start, end);

       }

   }

   public static void main(String[] args) {

       TowersOfHanoi towersOfHanoi = new TowersOfHanoi();

      

       // moves all pegs from A to C with the help of B

       towersOfHanoi.move(3, \"A\", \"B\", \"C\");

   }

}

/*

Sample run:

A -> C

A -> B

C -> B

A -> C

B -> A

B -> C

A -> C

*/

Write a recursive method that prints out the individual moves you need to perform to solve a Towers of Hanoi problem with n rings. while Using stacks to represe
Write a recursive method that prints out the individual moves you need to perform to solve a Towers of Hanoi problem with n rings. while Using stacks to represe

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site