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 #include 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); }
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.