Professional Documents
Culture Documents
PROGRAMMING
ASSIGNMENT-1:
TOWER OF HANOI
The Tower of Hanoi is the problem in which there are 3 towers, let’s mark it
with the names Source Pole, Temporary Pole, and Destination Pole. And in
Source Pole, we have n number of disks. And the task is to move all disks
from Source Pole to Destination Pole using Temporary Pole The puzzle
starts with the disks in a neat stack in ascending order of size on one
rod, the smallest at the top, thus making a conical shape. The objective
of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the upper disk from one of the
stacks and placing it on top of another stack or on an empty rod.
3. No larger disk may be placed on top of a smaller disk.
Understanding the Problem
Statement
The problem statement for the Tower of Hanoi is straightforward. The
goal is to move the entire stack of disks from the starting rod to the
final rod, adhering to the rules mentioned in the introduction section.
The number of disks in the stack can vary, and thus, the number of
moves required to solve the puzzle also varies.
For example, consider a scenario where we have three disks. In this
case, the minimum number of moves required to solve the puzzle is 7.
This can be calculated using the formula 2^n – 1, where n is the number
of disks. In general, the more disks we have in the stack, the more
moves are required to solve the puzzle.
And these n-1 moves are called recursively such that individual function call
is responsible to handle the 1 disk move in each call.
CODE IN PYTHON FOR TOWER OF HANOI:
def moveDisks(N, src, dst, temp):
if N > 0:
moveDisks(N - 1, src, temp, dst)
print('Move disk', N, 'from rod', src, 'to rod', dst)
moveDisks(N- 1, temp, dst, src)