Artificial Intelligence
Lecture # 18
Dr. Lubna Zafar
Lecturer
[email protected] Department of Computer Science & Information Technology
University of Poonch, Rawalakot Azad Kashmir
Dr. Lubna Zafar (Artificial Intelligence)
Towers of Hanoi Problem
Tower of Hanoi is a mathematical puzzle where we have three rods (A, B,
and C) and N disks.
Initially, all the disks are stacked in decreasing value of diameter i.e., the
smallest disk is placed on the top and they are on rod A.
The objective of the puzzle is to move the entire stack to another rod (here
considered C), obeying the following simple rules:
Dr. Lubna Zafar (Artificial Intelligence)
Towers of Hanoi Problem
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
Dr. Lubna Zafar (Artificial Intelligence)
Example 1
Only one disk can be moved at a time.
Input: 2
Output:
Disk 1 moved from A to B
Disk 2 moved from A to C
Disk 1 moved from B to C
Dr. Lubna Zafar (Artificial Intelligence)
Example 2
Only one disk can be moved at a time.
Input: 3
Output:
Disk 1 moved from A to C
Disk 2 moved from A to B
Disk 1 moved from C to B
Disk 3 moved from A to C
Disk 1 moved from B to A
Disk 2 moved from B to C
Disk 1 moved from A to C
Dr. Lubna Zafar (Artificial Intelligence)
Towers of Hanoi Problem – 3 disks
The idea is to use the helper node to reach the destination using
recursion.
Below is the pattern for this problem:
Shift ‘N-1’ disks from ‘A’ to ‘B’, using C.
Shift last disk from ‘A’ to ‘C’.
Shift ‘N-1’ disks from ‘B’ to ‘C’, using A.
Dr. Lubna Zafar (Artificial Intelligence)
Towers of Hanoi Problem – 3 disks
Dr. Lubna Zafar (Artificial Intelligence)
Solution
Follow the steps below to solve the problem:
Create a function towerOfHanoi where pass the N (current
number of disk), from_rod, to_rod, aux_rod.
Make a function call for N – 1 th disk.
Then print the current disk along with from_rod and to_rod
Again make a function call for N – 1 th disk.
Dr. Lubna Zafar (Artificial Intelligence)
Implementation
Below is the implementation of the given approach.
# Recursive Python function to solve tower of hanoi
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n == 0:
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk", n, "from rod", from_rod, "to rod",
to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
Dr. Lubna Zafar (Artificial Intelligence)
Implementation
# Driver code
N=3
# A, C, B are the name of rods
TowerOfHanoi(N, 'A', 'C', 'B')
Dr. Lubna Zafar (Artificial Intelligence)
Output
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Dr. Lubna Zafar (Artificial Intelligence)