Saturday 4 January 2014

Tower of HANOI:Complete Guide


Tower of HANOI



RULES::
The goal of the puzzle is to move all the disks from the leftmost peg to the rightmost peg, adhering to the following rules:
  1. Move only one disk at a time.
  2. A larger disk may not be placed ontop of a smaller disk.
  3. All disks, except the one being moved, must be on a peg.
Figure : Three-disk solution to the Towers of Hanoi puzzle.



\scalebox{0.9}{\includegraphics{eps/hanoi.eps}}

C PROGRAM TO SOLVE TOWER OF HANOI PROBLEM USING RECURSION

  1. /*
  2.  * C program for Tower of Hanoi using Recursion
  3.  */
  4. #include <stdio.h>
  5.  
  6. void towers(int, char, char, char);
  7.  
  8. int main()
  9. {
  10.     int num;
  11.  
  12.     printf("Enter the number of disks : ");
  13.     scanf("%d", &num);
  14.     printf("The sequence of moves involved in the Tower of Hanoi are :\n");
  15.     towers(num, 'A', 'C', 'B');
  16.     return 0;
  17. }
  18. void towers(int num, char frompeg, char topeg, char auxpeg)
  19. {
  20.     if (num == 1)
  21.     {
  22.         printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
  23.         return;
  24.     }
  25.     towers(num - 1, frompeg, auxpeg, topeg);
  26.     printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
  27.     towers(num - 1, auxpeg, topeg, frompeg);
  28. }

$ cc pgm11.c
$ a.out
Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :
 
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C



No comments:

Post a Comment