The Towers of Hanoi is a mathematical Puzzle. It consists of three rods (or pegs or towers) and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks on one rod in ascending order of size, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod.
Step 1 – Move the top n-1 disks from source to Auxiliary tower.
Step 2 – Move the nth disk from Source to Destination Tower
Step 3 – Move the n-1 disks from Auxiliary tower to Destination Tower
Transferring the top n-1 disks from source to auxiliary tower can be thought of a fresh problem and can be solved in the same manner.
Towers of Hanoi in Python –
def printMove(fr, to): print('move from ' + str(fr) + ' to ' + str(to)) def Towers(n, fr, to, spare): if n==1: printMove(fr, to) else: Towers(n-1, fr, spare, to) Towers(1, fr, to, spare) Towers(n-1, spare, to, fr)