Tower of Hanoi Problem in Python
 Tower of Hanoi; Tower of Hanoi Problem
Problem Statement
Tower of Hanoi is one of the classical problems of computer science. The problem states that ,
1. There are three stands on which a set of disks, each with a different diameter, are placed .
2. Initially, the disks are stacked on Stand 1 , in order of size, with the largest disk at the bottom .
The initial structure of Tower of Hanoi with three disk is shown in .Fig. 1
![]() |
Fig.1 Tower of Hanoi with Three Disks |
The "Tower of Hanoi problem" is to find a sequence of disk moves so that all the disks moved from Stand-1 to Stand-3, adhering to the following rules:
1. Moves only one disk at a time.
2. A larger disk cannot be placed on top of a smaller disk.
3. All disks except the one being moved should be on a stand .
The general strategy for solving the Tower of Hanoi Problem with in disks is shown in . Fig. 2
![]() |
Fig. 2. General strategy to Solve the Tower of Hanoi Problem with Three Disks |
The movement of n-1 disks forms the recursive case of recursive solution to move in disks. The base case of a solution involves the movement of only one disk . The recurrence relation for solving the Tower of Hanoi problem can be written as :
Tower of Hanoi (disks) = move the disk if disks = 1
Tower of Hanoi (disks-1) if disks > 1
Flow Chart
Recursive Algorithm
Hanoi (disk, source, dest, aux)
1. If only one disk is there then move disk from source to dest.
2. If more than one disk is there then
2.1 Recursively call Hanoi (disk-1, source, aux, dest)
2.1 Move disk from source to dest
2.3 Recursively call Hanoi (disk-1, aux, dest, source)
Pseudocode
START
Procedure Hanoi (disk, source, dest, aux)
IF disk ==1. THEN
move disk from source to dest
ELSE
Hanoi(disk -1, source, aux, dest)
move disk from source to dest
Hanoi(disk -1, aux, dest, source
END IF
END Procedure
STOP
Comments
Post a Comment