Tower of Hanoi, is a mathematical puzzle which consists of three towers.These rings are of varying sizes sizes and stacked upon each other in ascending order. There are other variations of the puzzle where the number of disks increase, but the tower count remains the same.
A few rules that need to be followed for Tower of Hanoi are -
1.The top disk can be moved only.
2.Only one disk can be moved at a time.
3.No large disk sits above a small disk.
Flowchart for Tower of Hanoi:
Algorithm for Tower of Hanoi:
Step 1: Start
Step 2: Let the three towers be source, dest, aux.
Step 3: Read number of disks, n from user.
Step 4: Move n-1 disks from source to aux.
Step 5: Move nth disk from source to dest.
Step 6: Move n-1 disks from aux to dest.
Step 7: Repeat Steps 3 to 5, by decrementing n by 1.
Step 8: Stop
In the above algorithm,
- Consider three towers source, dest, aux and take value of disks from the user.
- Now we move all the above n-1 disks one by one from source to aux.
- The largest disk is left at the source, which is then moved to the dest tower.
- Then again the rest of the disks are moved back from aux to source.
- Again the same steps are repeated so that all the disks are moved to the dest tower.