2
b. Solving the Towers of Hanoi problem.
#include<stdio.h>
#include<conio.h>
int count;
void main()
{
int n;
void THANOI(int,char,char,char);
clrscr();
printf("\n Enter the number of disks to be considered \n\n");
scanf("%d",&n);
THANOI(n,'A','C','B');
printf("\n Total number of moves= %d \n",count);
getch();
}
void THANOI(int n,char start,char end,char mid)
{
/* If only one disk, move it from A to C and return */
if(n = = 1)
{
printf("\n move disk %d from peg %c to peg %c\n",n,start,end);
count++;
getch();
return;
}
/* move top n-1 disks from A to B using C as auxiliary */
THANOI(n-1,start,mid,end);
/* move remaining disk from A to C */
printf("\n move disk %d from peg %c to peg %c\n",n,start,end);
count++;
getch();
/* move n-1 disk from B to C using A as auxiliary */
THANOI(n-1,mid,end,start);
}
Comments
Post a Comment