递归算法是我前些天写的,非递归是刚才找的,里面含递归和非递归。
递归算法:
#include <stdio.h>
//递归求汉诺塔问题
void hanoi(int n, char A, char B, char C, int *time)
{
if (n>=1)
{
hanoi(n-1, A, C, B, time);
move(A, C);
(*time)++;
hanoi(n-1, B, A, C, time);
}
}
//打印出每一步的路径
void move(char a, char c)
{
printf(" %c-->%c\n", a, c);
}
int main(void)
{
int n, time = 0;;
printf("请输入汉诺塔的盘数:");
scanf("%d", &n);
printf("%d个盘的汉诺塔移动方法是:", n);
printf("\n");
hanoi(n, 'A', 'B', 'C', &time);
printf("移动了%d次\n", time);
system("pause");
return 0;
}
非递归算法:
#include <stdio.h>
#define MAXSTACK 10 /* 栈的最大深度 */
int c = 1; /* 一个全局变量,表示目前移动的步数 */
struct hanoi { /* 存储汉诺塔的结构,包括盘的数目和三个盘的名称 */
int n;
char x, y, z;
};
void move(char x, int n, char y) /* 移动函数,表示把某个盘从某根针移动到另一根针 */
{
printf("%d-> %d from %c -> %c\n", c++, n, x, y);
}
void hanoi(int n, char x, char y, char z) /* 汉诺塔的递归算法 */
{
if (1 == n)
move(x, 1, z);
else {
hanoi(n - 1, x, z, y);
move(x, n, z);
hanoi(n - 1, y, x, z);
}
}
void push(struct hanoi *p, int top, char x, char y, char z,int n)
{
p[top+1].n = n - 1;
p[top+1].x = x;
p[top+1].y = y;
p[top+1].z = z;
}
void unreverse_hanoi(struct hanoi *p) /* 汉诺塔的非递归算法 */
{
int top = 0;
while (top >= 0) {
while (p[top].n > 1) { /* 向左走到尽头 */
push(p, top, p[top].x, p[top].z, p[top].y, p[top].n);
top++;
}
if (p[top].n == 1) { /* 叶子结点 */
move(p[top].x, 1, p[top].z);
top--;
}
if (top >= 0) { /* 向右走一步 */
move(p[top].x, p[top].n, p[top].z);
top--;
push(p, top, p[top+1].y, p[top+1].x, p[top+1].z, p[top+1].n);
top++;
}
}
}
int main(void)
{
int i;
printf("递归:\n");
hanoi(3, 'x', 'y', 'z');
printf("非递归:\n");
struct hanoi p[MAXSTACK];
c = 1;
p[0].n = 3;
p[0].x = 'x', p[0].y = 'y', p[0].z = 'z';
unreverse_hanoi(p);
return 0;
}
2019-07-17 22:54:28