Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Hide Buttons

Towers Of Hanoi

The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod.

The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:

  1. Only one disk is allowed to move at a time..
  2. Bigger disk cannot be placed on the top of smaller disk.

Tower-Of-Hanoi

Tower-Of-Hanoi

Approach:

  • Recursively Move N-1 disk from source to Auxiliary peg.
  • Move the last disk from source to destination.
  • Recursively Move N-1 disk from Auxiliary to destination peg.

Code:


Output:

Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C
Move disc 4 from A to B
Move disc 1 from C to B
Move disc 2 from C to A
Move disc 1 from B to A
Move disc 3 from C to B
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

  • Carlos de la Torre

    As a complement to your post, I think you will be interested in this: https://thewalnut.io/visualizer/visualize/1322/342/ Instead of using recursion, the solution is based on a really simple, iterative, program (available in the same site) that’s guaranteed to solve Towers of Hanoi in the minimum number of steps.

%d bloggers like this: