Showing posts with label Brahma's tower. Show all posts
Showing posts with label Brahma's tower. Show all posts

Saturday, 15 December 2012

TOWER OF HANOI- UNDERSTANDING THE RECURSION


PROBLEM: A stack of disks placed on pole A has to be moved to pole C using pole B as an intermediate pole for transition keeping in mind the condition that a disk of larger diameter cannot be place on that of a smaller diameter.   

SOLUTION : The very essence of solving this problem lies in understanding the recursive nature of the problem.Considering that there  'n' disks on pole A ;the problem can be broken into 3 repeating steps:

AIM: do something to move n disks from A to C using B.

step1: do something to move n-1 disks from A to B using C.

step2:move 'n' th disk from A to C.

step3:do something to move n-1 disks from B to C using A.

Note that the term "do something" is common with the AIM of procedure
steps 1 and 3 . Step 1 and 3 are itself new aims and will follow the same procedure (step 1,2,3 under the aim of step 1 )

Every time step 1 and step 3 will create a new set of procedure which again involve a sub set of procedures.

Here is a code for the tower of hanoi problem :

#include<stdio.h>
void tow(char x,char y,char z,int n);  // function declaration

int main()
{
int h;char a='a',b='b',c='c';
printf("enter the no of disk on stack a");
scanf("%d",&h);
printf("\nmovement of disks from stack a to stack c\n");
tow(a,b,c,h);                                         //function call
return 0;
}

void tow(char x,char y,char z,int n) // function
{
if(n-1>0)
 {
 tow(x,z,y,n-1);                                   // step1
 printf("\nmove  %d th  disk from %c to %c \n",n,x,z); //step2
 tow(y,x,z,n-1);                                  //step3
 }
else
 printf("move %d th disk from %c to %c \n",n,x,z);// when only one disk is left
}