Tuesday, 5 June 2012

C program to solve Towers of hanoi problem using recursion

#include<stdio.h>
#include<conio.h>
#include<math.h>
void  towers(int x, char source, char  destination,char  unwanted)
{
 if(x==1)
    printf("\n move the disk from %c to %c",source,destination);
 else
   {
     towers(x-1,source,unwanted,destination)
     /*    destination= unwanted;    unwanted=destination;   */


     printf("\n  Move disk from %c to %c\n", source,destination);


       towers(x-1,unwanted,destination,source);
       /*    source=unwanted;     unwanted=source;   */
   }
}
main()
{
 int totdisks,moves;
 clrscr();
 printf("\n Enter the number of disk you want to play with");
 scanf("\n %d",&totdisks);
 moves=pow(2,disks)-1;
 printf("\n The min no.of moves required to play is:%d\n",moves);
 towers(disk,A,B,C);
}



Working  Example:
let The number of disks be 3
and the towers are  A    B    C

towers(  3  , a    b   c)
{
   3!=1
  {
      towers(2,  a    c     b)
     {
       2!=1
       {
            towers(1, a   b   c)
           {
               1==1
                 {
                  move disk from a to b            
  //*******************       111111111111111    *************************
                 }7
            }   /* end of towers(1)
      
         move disk from  a to c                  
  //*********************    22222222222222222    *****************************
        towers(1,  b   c    a)
       {
          1==1
           {
        move   disk from   b    to    c  
//  ********************  33333333333333333  ***************************
             }      /*end of towers(1)  */
        }       /* end of towers(2);  */
       move disk from tower   a  to   b            
//  *********************  4444444444444444   ****************************

      towers( 2, c  a   b)
     {
       2!=1
          {
    towers(1  ,  c   b    a)
                  {
        1==1
        {
               move  disk from   c to   a      
  // ******************  555555555555555 *********************
          }   
    }/*     end of towers(1)

    move disk from c to  b                         
  //  *************************  66666666666666  *************************
          towers(1    a    b    c)
      {
        1==1

    {
    move    disk   from  a    to   b           
 //    ************************  777777777777777 ****************************
     }
}          



No comments:

Post a Comment