- 论坛徽章:
- 0
|
#include <stdio.h>
#include <stdlib.h>
typedef struct _HANNO
{
int n;
int from;
int to;
int temp;
} HANNO;
void hanno_run(int n, int from, int temp, int to);
int main(void)
{
hanno_run(3, 1, 2, 3);
return 0;
}
void hanno_run(int n, int from, int temp, int to)
{
int max = n * 2 - 1;
HANNO *hanno = (HANNO *)malloc(max * sizeof(HANNO));
HANNO *p = hanno;
int count = 0;
p->n = n;
p->from = from;
p->to = to;
p->temp = temp;
p++;
while (p > hanno)
{
p--;
from = p->from;
to = p->to;
n = p->n;
temp = p->temp;
if (1 == n)
{
count ++;
printf("%d -> %d\n", p->from, p->to);
continue;
}
p->n = n - 1;
p->from = temp;
p->to = to;
p->temp = from;
p++;
p->n = 1;
p->from = from;
p->to = to;
p->temp = temp;
p++;
p->n = n - 1;
p->from = from;
p->to = temp;
p->temp = to;
p++;
}
free(hanno);
printf("total %d steps.\n", count);
}
|
|
|