Tower of Hanoi using c language
Tower of Hanoi
The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. He was inspired by a legend that tells of a Hindu temple where the puzzle was presented to young priests. At the beginning of time, the priests were given three poles and a stack of 64 gold disks, each disk a little smaller than the one beneath it. Their assignment was to transfer all 64 disks from one of the three poles to another, with two important constraints. They could only move one disk at a time, and they could never place a larger disk on top of a smaller one. The priests worked very efficiently, day and night, moving one disk every second. When they finished their work, the legend said, the temple would crumble into dust and the world would vanish.Although the legend is interesting, you need not worry about the world ending any time soon. The number of moves required to correctly move a tower of 64 disks is
Figure 1 shows an example of a configuration of disks in the middle of a move from the first peg to the third. Notice that, as the rules specify, the disks on each peg are stacked so that smaller disks are always on top of the larger disks. If you have not tried to solve this puzzle before, you should try it now. You do not need fancy disks and poles–a pile of books or pieces of paper will work.
Here is a high-level outline of how to move a tower from the starting pole, to the goal pole, using an intermediate pole:
- Move a tower of height-1 to an intermediate pole, using the final pole.
- Move the remaining disk to the final pole.
- Move the tower of height-1 from the intermediate pole to the final pole using the original pole.
program:
# include <stdio.h>
/* Definition of the Tower Of Hanoi generator function */
void TowerOfHanoi(char peg1, char peg2, char peg3, int no)
{
if (no==1)
printf(" Move Disk from %c ==> %c\n", peg1, peg3);
else
{
TowerOfHanoi(peg1, peg3, peg2, no-1);
TowerOfHanoi(peg1, peg2, peg3, 1);
TowerOfHanoi(peg2, peg1, peg3, no-1);
}
}
/* main function */
int main()
{
int noDisks;
// clrscr();
printf("Solving Tower of Hanoi puzzle\n\n");
printf("Input the number of disc: ");
scanf("%d", &noDisks);
if (noDisks<=0)
printf("No of disks = %d is an INVALID value\n", noDisks);
else
{
printf("Moving %d disks from peg A to peg C\n\n");
TowerOfHanoi('A', 'B', 'C', noDisks);
}
// getch();
}
No comments:
Post a Comment