key to solving this puzzle is to recognize that it can be solved by breaking the problem down into a collection of smaller problems and further breaking those problems down into even smaller problems hence making it a typical best suited problem for recursion .
example: the pegs are A, B, C and n is the total number of discs number the discs from 1 the largest of the discs and 5(variable DISCS) the smallest.
move n−1 discs from A to B. This leaves disc n alone on peg A
move disc n from A to C
move n−1 discs from B to C so they sit on disc n
The above is a recursive algorithm, to carry out steps 1 and 3, apply the same algorithm again for n−1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1.
here is the program/code in c
NOTE : the number of discs is stored in predefined in DISCS , which can be changed to any value . But for every ring added the algorithm will take twice the time and memory for computation hence the following code may fail for values above 10 for DISCS
example: the pegs are A, B, C and n is the total number of discs number the discs from 1 the largest of the discs and 5(variable DISCS) the smallest.
move n−1 discs from A to B. This leaves disc n alone on peg A
move disc n from A to C
move n−1 discs from B to C so they sit on disc n
The above is a recursive algorithm, to carry out steps 1 and 3, apply the same algorithm again for n−1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1.
here is the program/code in c
- #include<stdio.h>
- #define P(x) printf("%d\n",x);
- #define Ps(x) printf("\n\n%s=\n",x)
- #define DISCS 10
- struct stack1
- {int a[10],top;
- };
- typedef struct stack1 stack;
- initialize(stack *s1,stack *s2,stack *s3)
- {
- s1->top=s2->top=s3->top=-1;
- }
- int push(stack *s,int x)
- {
- return(s->top<=(DISCS-2)?s->a[++s->top]=x,1:0);
- }
- int pop(stack *s)
- {
- return(s->top==-1?-999:s->a[s->top--]);
- }
- move(stack *s1,stack *s2)
- {
- int x=pop(s1);
- push(s2,x);
- }
- printstack(stack *s3)
- { int to=s3->top,d=pop(s3);
- for(;!(d==-999);d=pop(s3))P(d);
- s3->top=to;
- }
- tower_of_hanoi(stack *t1,stack *t2,stack *t3,int pgs)
- { //you can print the stack here also, after each function call
- if(pgs>0){
- tower_of_hanoi(t1,t3,t2,pgs-1);
- move(t1,t2);
- tower_of_hanoi(t3,t2,t1,pgs-1);
- }
- }
- main()
- {
- stack s1,s2,s3;
- initialize(&s1,&s2,&s3);
- int d=1;//pegs 1 being the largest and DISCS the smallest
- for(;push(&s1,d++););
- Ps("orig/first stack");
- printstack(&s1);
- tower_of_hanoi(&s1,&s2,&s3,DISCS);
- Ps("first stack");
- printstack(&s1);
- Ps("second stack");
- printstack(&s2);
- Ps("third stack");
- printstack(&s3);
- }
NOTE : the number of discs is stored in predefined in DISCS , which can be changed to any value . But for every ring added the algorithm will take twice the time and memory for computation hence the following code may fail for values above 10 for DISCS