Challenge: Tower of Hanoi

Let’s solve the Tower of Hanoi problem using recursion.

Problem

We are given three rods in the Tower of Hanoi and n disks. Initially, all the disks are added to the first rod (the leftmost one) such that no smaller disk is under the larger one. The objective is to transfer the entire stack of disks from the first tower to the third tower (the rightmost one), moving only one disk simultaneously. Moving a larger disk onto a smaller one is not allowed.

Input

nn number of disk and three rods.

Output

Sequence of moves.

Sample input

towerOfHanoi(3, 'A', 'C', 'B')

Sample output

The sequence of moves involved in the Tower of Hanoi are :
Move 1st disk from peg A to peg C 
Move 2nd disk from peg A to peg B 
Move 1st disk from peg C to peg B 
Move 3rd disk from peg A to peg C 
Move 1st disk from peg B to peg A 
Move 2nd disk from peg B to peg C 
Move 1st disk from peg A to peg C 

Let’s look at the illustration below to better understand the problem.

Get hands-on with 1400+ tech skills courses.