Sunday, September 29, 2013

Tower Of Hanoi Continued...

As I have described in the previous post , Here is the Recursion Tree of the Tower. If you are able to draw the recursion tree of a a problem you will be able to code that too very easily.




This Tree is self explanatory , In this we have Decomposed the 3 Disc problem into 3 steps and recursively solved the same.

So, Now we can write the Program for the same , It does not depend which programming language you use to code , the algorithm will be the same.

Tower Of Hanoi Algorithm Implementation.

#include<stdio.h>
int main()
{
int number_of_discs;
printf("Enter the Number of discs:");
scanf("%d",&number_of_discs);
printf("\n");
Towers(number_of_discs,'A','B','C');
}

void Towers(int N,char From, char To, char Via)
{
   if(N==1)
{
printf("Moving %c to %c\n ", From , To);
}
else
{
  Towers(N-1,From,Via,To);                     //(N-1,A,C,B)
  printf("Moving %c to %c\n" , From , To);    //(1,A,B,C)
  Towers(N-1,Via, To,From);                   //(N-1,C,B,A)
}

}

No comments:

Post a Comment

Feel free to comment......