You are on page 1of 8

Tower Of

Hanoi
A RT I F I C I A L
INTELLIGENCE LAB

BY: HIRA FARMAN


TOWER OF HANOI
The Tower of Hanoi (also called the Tower of Brahma or Lucas' Tower and sometimes
pluralized as Towers) is a mathematical game or puzzle. It consists of three rods and a
number of disks of different sizes, which can slide onto any rod. 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.

BY: HIRA FARMAN


Program for Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the
entire stack to another rod, obeying the following simple rules:

Rules
The mission is to move all the disks to some another tower without violating the sequence of
arrangement. A few rules to be followed for Tower of Hanoi are −

• Only one disk can be moved among the towers at any given time.

• Only the "top" disk can be removed.

• No large disk can sit over a small disk.

BY: HIRA FARMAN


Approach :
Take an example for 2 disks :

Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.

Step 1 : Shift first disk from 'A' to 'B'.

Step 2 : Shift second disk from 'A' to 'C'.

Step 3 : Shift first disk from 'B' to 'C'.

The pattern here is :

Shift 'n-1' disks from 'A' to 'B'.

Shift last disk from 'A' to 'C'.

Shift 'n-1' disks from 'B' to 'C'.

BY: HIRA FARMAN


Examples:
Input : 2 Input : 3
Output :
Output : Disk 1 moved from A to C
Disk 1 moved from A to B Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 2 moved from A to C Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 1 moved from B to C Disk 2 moved from B to C
Disk 1 moved from A to C

BY: HIRA FARMAN


CODE HINT:
class Problem:
def __init__(self, initial, goal=None):

def successor(self, state):

def goal_test(self, state):

def path_cost(self, c, state1, action, state2):

BY: HIRA FARMAN


LIVE DEMO
HTTPS://WWW.KHANACADEMY.ORG/COMPUTING/COMPUTE
R-SCIENCE/ALGORITHMS/TOWERS-OF-HANOI/E/MOVE-THR
EE-DISKS-IN-TOWERS-OF-HANOI

BY: HIRA FARMAN


REFERENCE:
https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/?ref=lbp

BY: HIRA FARMAN

You might also like