Tower of Hanoi
Tower of Hanoi
• These disks are continuously moved by priests in the temple. According to a prophecy,
when the last move of the puzzle is completed the world will end.
• These priests acting on the prophecy, follow the immutable rule by Lord Brahma of
moving these disk one at a time.
These discs are of different sizes and stacked upon in an ascending order, i.e. the smaller one
sits over the larger one. There are other variations of the puzzle where the number of discs
increase, but the tower count remains the same.
Rules
The mission is to move all the discs to some another tower without violating the sequence of
arrangement. A few rules to be followed for Tower of Hanoi are −
• Only one disc can be moved among the towers at any given time.
• Only the "top" disc can be removed.
• No large disc can sit over a small disc.
Tower of Hanoi puzzle with n discs can be solved in minimum 2n−1 steps it shows that a
puzzle with 3 discs has taken 23 - 1 = 7 steps.
Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem
with lesser number of discs, say → 1 or 2. We mark three towers with
name, source(A), destination(C) and aux(B) (only to help moving the discs). If we have only
one disc, then it can easily be moved from source to destination peg(or tower).
If we have 2 discs −
So now, we are in a position to design an algorithm for Tower of Hanoi with more than two
disc. We divide the stack of discs in two parts. The largest disc (nth disk) is in one part and all
other (n-1) discs are in the second part.
Our ultimate aim is to move disc n from source to destination and then put all other (n1) discs
onto it. We can imagine to apply the same in a recursive way for all given set of discs.
The steps to follow are −
Step 1 − Move n-1 discs from A to B using C
Step 2 − Move nth disc from A to C
Step 3 − Move n-1 discs from B to C using A
A recursive algorithm for Tower of Hanoi can be driven as follows −