Explain Tower Of Hanoi Problem?

Data Structure >   Stack Data Structure >   Stack operations and Implementation  

Long Question

581


Answer:

The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in 1883. We are given a tower of Three disks, initially stacked in increasing size on one of three pegs. The objective is to transfer the entire tower to one of the other pegs (the rightmost ), moving only one disk at a time and never a larger one onto a smaller.

Solution for N=3
1. Move from Src to Dst
2. Move from Src to Mid
3. Move from Dst to Mid
4. Move from Src to Dst
5. Move from Mid to Src
6. Move from Mid to Dst
7. Move from Src to Dst

Recursive Algorithm for Tower of Hanoi


TowerOfHanoi(N, Src, Mid, Dst)
if N is 0
exit
else

TowerOfHanoi(N - 1, Src, Dst, Mid)
Move from Src to Dst
TowerOfHanoi(N - 1, Mid, Src, Dst)

Program for explain tower of Hanoi problem


#include<conio.h>
#include<stdio.h>
void towers(int,char,char,char);
void main()
{
int n;
clrscr();
printf("Enter the no.of elements:");
scanf("%d",&n);
towers(n,'a','c','b');
getch();
}
void towers(int n,char frompeg,char topeg,char auxpeg)
{
if(n==1)
{
printf("\n%s%c\t%s%c","movedisk1 frompeg",frompeg,"topeg",topeg);
return;
}
towers(n-1,frompeg,auxpeg,topeg);
printf("\n%s%d\t%s%c\t%s%c","movedisk",n,"frompeg",frompeg,"top
eg",topeg);
towers(n-1,auxpeg,topeg,frompeg);
}


This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.