c - moving of disc in tower of hanoi -
please explain me recursion process step step using f7.
i can't correlate return flow of control.
#include<stdio.h> #include<conio.h> void t_of_h(char, char, char, int); void main() { int n; clrscr(); printf("enter no of disc in tower of hanoi : "); scanf("%d",&n); printf("\ntower of hanoi using %d discs\n",n); t_of_h('x', 'y', 'z', n); getch(); } void t_of_h(char p1, char p2, char p3, int n) { if(n==0) printf("unsuccessful move\n"); if(n==1) printf("move disc %c %c\n",p1,p3); else { t_of_h(p1,p3,p2,n-1); t_of_h(p1,p2,p3,1); t_of_h(p2,p1,p3,n-1); } }
how move n disks tower tower b?
- move n-1 disks tower tower c.
- move bottom disk tower tower b.
- move n-1 disks tower c tower b.
the code pretty direct implementation of that. if assume can move arbitrary number of disks 1 tower another, works. how move n-1 disks tower tower c? well, move n-2 disks tower tower b, move n-1th disk tower tower c, move n-2 disks form tower b tower c. , repeat...
eventually, recursion stops because have single disk move.
an interesting exercise "write test harness ensures no invalid moves ever made".
ok - i've run code. visualization of process gruesome. hard see going on. direct report of algorithm does. what?
1 disk
enter no of disc in tower of hanoi : 1 tower of hanoi using 1 discs move disc x z
2 disks
enter no of disc in tower of hanoi : 2 tower of hanoi using 2 discs move disc x y move disc x z move disc y z
note moving disks x z. how move 2 disks x z? move top disk x y. move bottom disk x z. move original top disk y z.
3 disks
enter no of disc in tower of hanoi : 3 tower of hanoi using 3 discs move disc x z move disc x y move disc z y move disc x z move disc y x move disc y z move disc x z
Comments
Post a Comment