void hanoi(int n, int a, int b, int c) // a=beginning b=middle c=destination
{
if (n==1)
printf("\nmove %d to %d", a, c);
else
{
hanoi(n-1, a, c, b);
printf("\nmove %d to %d", a, c);
hanoi(n-1, b, a, c);
}
}
void main()
{
int n=1;
char input[20];
printf("\n | | | towers");
printf("\n - | | of");
printf("\n --- | | hanoi -");
printf("\n ----- | | Enter the number of rings: ");
Discussion (7)
/*
Jim Snow
3-3-1998
*/
#include <stdio>
#include <stdlib>
void hanoi(int n, int a, int b, int c) // a=beginning b=middle c=destination
{
if (n==1)
printf("\nmove %d to %d", a, c);
else
{
hanoi(n-1, a, c, b);
printf("\nmove %d to %d", a, c);
hanoi(n-1, b, a, c);
}
}
void main()
{
int n=1;
char input[20];
printf("\n | | | towers");
printf("\n - | | of");
printf("\n --- | | hanoi -");
printf("\n ----- | | Enter the number of rings: ");
fgets(input, 20, stdin);
n=atoi(input);
if (n>0)
hanoi(n, 1, 2, 3);
printf("\n");
}
jyte needs a way to hide spoilers. ( :
are you Jim Snow, Elihu?
That's me. Sorry, I didn't realize posting a solution would spoil the fun.
If I remember correctly, the easiest solution was recursive.
Although, now that I think about it ... is there even a nonrecursive solution?
I was kidding about the spoiler warning.
and yes, there are non-recursive solutions. follow the link in the description for more information.
A word of warning: solving for n=64 will cause the world to end.
"Although, now that I think about it ... is there even a nonrecursive solution? "
Yes. It is provable that every recursive algorithm has an iterative counterpart.
D'A