Towers Of Hanoi

The Tower of Hanoi is a math­e­mat­i­cal game or puz­zle. It con­sists of three rods, and a num­ber of disks of dif­fer­ent sizes which can slide onto any rod.

The objec­tive of the puz­zle is to move the entire stack to another rod, obey­ing the fol­low­ing sim­ple rules:

  1. Only one disk is allowed to move at a time..
  2. Big­ger disk can­not be placed on the top of smaller disk.

Tower-Of-Hanoi

Tower-Of-Hanoi

Approach:

  • Recur­sively Move N-1 disk from source to Aux­il­iary peg.
  • Move the last disk from source to destination.
  • Recur­sively Move N-1 disk from Aux­il­iary to des­ti­na­tion peg.

Code:


Out­put:

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

You may also like...

  • Car­los de la Torre

    As a com­ple­ment to your post, I think you will be inter­ested in this: https://thewalnut.io/visualizer/visualize/1322/342/ Instead of using recur­sion, the solu­tion is based on a really sim­ple, iter­a­tive, pro­gram (avail­able in the same site) that’s guar­an­teed to solve Tow­ers of Hanoi in the min­i­mum num­ber of steps.