Towers of Hanoi Every budding computer scientist must grappl
(Towers of Hanoi) Every budding computer scientist must grapple with certain classic problems, and the Towers of Hanoi is one of the most famous. Legend has it that in a temple in the Far East, priests are attempting to move a stack of disks from one peg to another. The initial stack has 64 disks stacked onto one peg and arranged from bottom to top by decreasing size. The priests are attempting to move the stack from this peg to a second peg under the constraints that exactly one disk is moved at a time and at no time may a larger disk be placed above a smaller disk. A third peg is available for temporarily holding disks. Supposedly, the world will end when the priests complete their task, so there is little incentive for us to facilitate their efforts.
Which by the way, will take 18,446,744,073,709,551,615 moves. If we assume one second per move, 24 hours a day, non-stop - it will take the monks 584,942,417,355 years to move all the disks from one peg to the other. In case you were wondering when the earth was ending.
Les us assume that the priests are attempting to move the disks from peg 1 to peg 3. We wish to develop an algorithm that will print the precise sequence of peg-to-peg disk transfers.
If we were to approach this problem with conventional methods, we would rapidly find ourselves hopelessly knotted up in managing the disks. Instead, if we attack the problem with recursion in mind, it immediately becomes tractable. Moving n disks can be viewed in terms of moving only n – 1 disks (and hence the recursion) as follows:
Solution
#include int move (int n, int sp, int ep, int hp);
int main(void)
{
int move (int n, int sp, int ep, int hp);
int n = 0;
int sp = 0;
int ep = 0;
int hp = 0;
int wait;
printf(\"Enter number of disks: \");
scanf_s(\"%d\", &n);
printf(\"Enter start peg (1-3): \");
scanf_s(\"%d\", &sp);
printf(\"Enter end peg (1-3): \");
scanf_s(\"%d\", &ep);
if ( sp == ep )
{
printf(\"Nice try\");
return 0;
}
if (( sp == 1 && ep ==2)|| (sp ==2 && ep == 1)) hp = 3;
if (( sp == 1 && ep ==3) || (sp ==3 && ep == 1)) hp = 2;
if (( sp == 2 && ep ==3) || (sp ==3 && ep == 2)) hp = 1;
printf(\"\ \ Move %d disks from peg %d to peg %d using %d as a holding peg\ \ \", n, sp , ep , hp);
move (n , sp , ep , hp); scanf_s(\"%d\", &wait);
return 0;
}
int move ( int n, int sp, int ep, int hp )
{ if (n==1)
{
printf(\"Move disk from %d--->%d\ \", sp , ep);
}
else { move ( (n-1), sp, hp, ep );
printf(\"Move disk from %d--->%d\ \", sp , ep);
move ( (n-1), hp, ep, sp );
}
return n;

