Sunday, July 4, 2010

PROGRAM TO IMPLEMENT TOWERS OF HANOI(DS)

Buzz It

#include<iostream.h>
#include<conio.h>
class hanoi
{
int n;
public:
void solution(char,char,char,int);
};
void hanoi::solution(char t1,char t2,char t3,int n)
{
if(n==1)
{
cout<<"move the top disk from
tower"<<"\t"<<t1<<"\t"<<"to"<<"\t"<<t2<<"\n";
return;
}
solution(t1,t3,t2,n-1);
cout<<"move the top disk from
tower"<<"\t"<<t1<<"\t"<<"to"<<"\t"<<t2<<"\n";
solution(t3,t2,t1,n-1);
}
void main()
{
clrscr();
hanoi ob;
int n;
char t1='a',t2='b',t3='c';
cout<<"enter number of disks\n";
cin>>n;
if(n<1)
{
cout<<"nothing to move";
}
else
{
ob.solution(t1,t2,t3,n);
}
getch();
}

OUTPUT:
enter number of disks
3
move the top disk from tower a to b
move the top disk from tower a to c
move the top disk from tower b to c
move the top disk from tower a to b
move the top disk from tower c to a
move the top disk from tower c to b
move the top disk from tower a to b

0 comments:

Post a Comment