Write an algorithm for getting solution to the Tower's of Hanoi problem. Explain the working of your algorithm (with 4 disks) with appropriate diagrams.
Ans:
void Hanoi(int n, char initial, char temp, char final)
{ if(n==1)
{ printf("move disk 1 from peg %c to peg%c\n",initial,final);
return;
}
Hanoi(n-1,initial, final, temp);
printf("move disk %d from peg %c to peg%c\n", n, initial, final);
Hanoi(n-1,temp,initial,final);
}
For n=4, let A, B and C denotes the initial, temp and final peg respectively. Using above algorithm, the recursive solution for n=4 disks comprises of the following 15 moves:
![1549_Hanoi problem.png](https://www.expertsmind.com/CMSImages/1549_Hanoi problem.png)