2. Tower of Hanoi (TOH)
• In tower of Hanoi we have N disks in tower
A.
• We are suppose to go all N disks from
tower A to C in a such way that smaller
disk always appears on larger disk.
• To solve this problem we have give the
extra tower B.
3. Rules for Tower of Hanoi
• Only one disk can be moved at a time.
• No larger disk can appears on a smaller
disk.
• Only one top most disk can be moved
from one tower and it can appear only at
the top most position of another tower.
• You are to transfer all disk to the right
hand tower in the fewest possible.
4. Algorithm for TOH
• // N : no of disks
• // A,B,C : towers
if (n>=1)
{
TOH (n-1,A,C,B)
print (A->C)
TOH (n-1,B,A,C)
}
5.
6.
7.
8.
9. No of movements in TOH
No of disks movement
1 1
2 3
3 7
4 15
5 31
Due to this we can say that no of
movement=2^n -1
10. #include<stdio.h>
#include<conio.h>
void TOH(int,char,char,char);
int count=0;
void main()
{
int n;
clrscr();
printf("enter no of disks");
scanf("%d",&n);
TOH(n,'A','B','C');
printf("total no of movement=%d",count);
getch();
}
void TOH(int n,char a, char b,char c)
{
if(n>=1)
{
TOH(n-1,a,c,b);
printf("n move %c -> %c",a,c);
Programming for TOH