Monday 1 February 2016

Tower of Hanoi-Solution

python-tower-of-hanoi The Game

Tower of Hanoi is a puzzle game. Your objective is to move disks from one tower to another tower. You initially have 3 towers of which two are empty and one(say tower 1) contains n disks. These n disks are all of different sizes. In tower 1 they are present in definite order- the largest at the botttom and the smallest at the top. You can only move one disk at a time. The rule is that you cannot place a bigger disk on a smaller disk. This relocation of disks needs to be done in minimum number of moves.



Solution

The most easy solution to this solution is using recursion.  I have implemented this program using Python language by using recursive function called toh. The number of minimum moves increases exponentially with an increase in the number of disk. By adding one extra disk the number of moves to solve the puzzle nearly double. To solve this game the number of minimum moves is given by

Moves=2^n-1
where n is the number of disks.

Code

def toh(n,x,y,z):  #function to find the solution
    if n>=1:
        toh(n-1,x,z,y)
        print "move disk from ",x," to ",y
        toh(n-1,z,y,x)


print "Program for Tower of Hanoi Solution"
print "Program by Abhishek Munagekar for Programing Wonders"
print "Enter small values for n like upto 15, otherwise it will take more time"
print "The number of steps to solve is exponential"
print "The solution is based on recursive algorithm"
print "The Program will display the optimum solution to transfer the disks from Tower A to Tower B"
num=input("Enter the number of disks in tower A:-");
toh(num,"towerA","towerB","towerC")

Ouput


Program for Tower of Hanoi Solution
Program by Abhishek Munagekar for Programing Wonders
Enter small values for n like upto 15, otherwise it will take more time
The number of steps to solve is exponential
The solution is based on recursive algorithm
The Program will display the optimum solution to transfer the disks from Tower A to Tower B
Enter the number of disks in tower A:-3
move disk from  towerA  to  towerB
move disk from  towerA  to  towerC
move disk from  towerB  to  towerC
move disk from  towerA  to  towerB
move disk from  towerC  to  towerA
move disk from  towerC  to  towerB
move disk from  towerA  to  towerB

Suggested

Download an app for Tower of Hanoi if you haven't played the game before. 


Image Source
Owner:-https://pixabay.com/en/users/Peggy_Marco-1553824/
https://pixabay.com/en/eiffel-tower-paris-eifel-france-1020299/



No comments:

Post a Comment