Towers Of Hanoi Algorithm

The towers of hanoi is a mathematical puzzle. We have three towers (or rods or pegs), and a number of disks of different sizes which can slide into any tower.

The puzzle starts with the disks on one tower in ascending order of size, the smallest at the top, making a conical shape.

The objective of the puzzle is to move entire stack on another tower with satisfying below rules:

Rules
  • Only one disk can be moved at a time.
  • Each move consists of taking the upper disk from one of the towers and sliding it onto another tower, on top of the other disks that may already be present on that tower.
  • No disk can be placed on top of a smaller disk.
Towers Of Hanoi
Towers Of Hanoi
Algorithm
  1. Move the top n-1 disks from source to auxiliary tower.
  2. Move the nth disk from source to destination tower.
  3. Move the n-1 disks from auxiliary tower to destination tower.
  4. Now, transferring the top n-1 disks from source to auxiliary tower can be thought as a fresh problem and can be solved in the same manner using recursion.
  5. Once we solve Towers Of Hanoi with three disks, we can solve it with any number of disks with the same algorithm.
Java Program of Towers Of Hanoi

Output

Enter number of disks :- 3 Move disks as below illustration. A –> C A –> B C –> B A –> C B –> A B –> C A –> C
It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *