c - Understanding recursive solution to Towers of Hanoi -
this question has answer here:
- tower of hanoi: recursive algorithm 22 answers
can please explain program? want know how parameters passed function tower
, how recursion works.
here code:
#include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("enter no. of disks"); scanf("%d",&n); tower(n,'s','d','t'); getch(); } tower(int n,char source,char dest,char temp) { if(n>0) { tower(n-1,source,temp,dest); printf("\nmove disk %d %c %c",n,source,dest); tower(n-1,temp,dest,source); } return; }
this program illustrates solution tower of hanoi problem.
so have pile 1 n disks , 2 other empty pile 2 , 3. need move n disks pile 1 pile 3(or 1 2, not matter).
if imagine n disks (n-1 disks) , 1 disk, problem becomes simple: move (n-1) pile 2 , last disk pile 3.
so need work out how move (n-1) disks pile 1 pile 2, means have exact problem n-1 disks. repeat process , you'll point need move 1 disk pile 1 pile 2.
Comments
Post a Comment