Challenge: Recursive Towers of Hanoi
Apply what you’ve learned about recursion in the coding exercises in this lesson.
We'll cover the following...
Problem statement
Given 3 Pegs—A, B, and C—and n Disks, all on peg A, move all disks to Peg C.
void move(int n, char sp, char ap, char ep);
📝 Note:
spwill be the first peg,A,apwill be the second peg,B, andepwill be the third peg,C.
Move all the disks from peg A to peg C. The figure given below shows the classical Towers of Hanoi problem that can be solved using recursion.
Rules:
- Only one disk can be moved at a time.
- The larger disk cannot be placed on the smaller disk.
Your task is to follow the rules stated above and indicate (as output) the moves that need to be made to move n disks from peg A to peg C, using peg B as an intermediate peg.
Hint
Movement of 3 disks from A to C can be expressed in the form of itself, so we can implement it through recursion.
The movement is done in three distinct steps. We would have to write calls to the recursive functions to execute these steps as you would implement in your solution.
Try to move the disks from peg A to peg C in the widget given below. You need to drag the disk from the source peg and, then, drop it to the target peg. Press the Restart button to restore the initial state.
Sample input
move(24)
Sample output
Move from A to C
Move from A to B
Move from C to B
Move from A to C
Move from B to A
Move from B to C
Move from A to C
📝 Note: You have to print your output on the console in the given format.
Coding exercise
Before diving directly into the solution, first, try to solve it yourself, and, then, check if your code passes all the test cases. If you get stuck, you can always see the given solution.
⚠️ Warning: Your function name should be
move. Otherwise, your code will not compile.
Good Luck! 👍