Lecture 7A - Recursive Function - Tower of Hanoi
Lecture 7A - Recursive Function - Tower of Hanoi
(Tower of Hanoi)
What is Tower of Hanoi?
The Towers of Hanoi is a well-known children’s game, played
with three poles and a number of different-sized disks. Each disk
has a hole in the center, allowing it to be stacked around any of
the poles. Initially, the disks are stacked on the leftmost pole in
the order of decreasing size, i.e., the larger on the bottom and
the smallest on the top. The objective of the game is to transfer
the disks from the leftmost pole to the rightmost pole, without
ever placing a larger disk on the top of a smaller disk. Only one
disk may be moved at a time and each disk must always placed
around one of the poles.
Tower of Hanoi
Task: Conditions:
Move all disks from 1. Only one disk can be moved at a time.
pole (s) to pole (d). 2. A larger disk cannot be placed on top of a smaller disk
3. Pole (h) can be used as a helping pole.
Tower of Hanoi -Solution
For n = 1
For n = 5
Recursive Definition:
1. Termination: if only one
disk, move from (s) to (d).
2. Reduction: if n (n > 1) disks,
then follow the steps: (s) (h) (d)
(a) move (n-1) disks from
(s) to (h). void Hanoi(int n, int s, int h, int d){
(b) move remaining 1 disk
if ( n == 1) movedisk(s, d);
from (s) to (d)
(c) move (n-1) disks from else{
(h) to pole (d) Hanoi(n-1, s, d, h)
movedisk(s, d);
Hanoi(n-1, h, s, d);
}
}
Tower of Hanoi – Program
#include <stdio.h>
void Hanoi(int, int, int, int);
int main(){
int n;
Description
if ( n == 1) m(s, d);
else{
For n = 4.
H(n-1, s, d, h)
m(s, d);
H(n-1, h, s, d);
}
}
How many movements are required?
void H (n, s, h, d){
if ( n == 1) m(s, d);
else{
H(n-1, s, d, h)
m(s, d);
H(n-1, h, s, d);
}
}