/**
* @file Hanoi.c
* @brief
* <li>Function: Hanoi塔的递归以及非递归解法</li>
* <li>Design Points:</li>
* <p>
*
* </p>
* @author Administrator
* @date 2010-10-21
*
*/
#include <stdio.h>
#define A (0x01)
#define B (0x02)
#define C (0x04)
#define MASK (0x07)
#define STK_SIZE 40 /*非递归解法的栈大小*/
/*获取除first和second另外一个柱子*/
#define OTHER(first,second) (~((first) | (second)) & MASK)
typedef unsigned char Column;
/**
* 打印时结果时的字符转换
*/
char transfer(Column c)
{
switch (c)
{
case A:
return 'A';
case B:
return 'B';
case C:
return 'C';
default:
return 'X';
}
}
/**
* 将盘子从from移动至to
*/
void move(Column from, Column to)
{
char chfrom = transfer(from);
char chto = transfer(to);
printf("move from %c to %c\n", chfrom, chto);
}
/**
* 递归解法
*/
void recursHanoi(Column from, Column to, int num)
{
if (num == 1)
{
move(from, to);
return;
}
Column other = OTHER(from,to);
recursHanoi(from, other, num - 1);
move(from, to);
recursHanoi(other, to, num - 1);
return;
}
typedef struct
{
Column src;
Column dst;
int num; /*需要移动的盘子数*/
int state;
} Attempt;
/**
* 非递归解法
* 针对求解的二叉树构造中序遍历
*/
void norecurseHanoi(Column from, Column to, int num)
{
Attempt firtattp = { from, to, num, 0};
Attempt stk[STK_SIZE]; /*申明堆栈*/
int top = -1; /*栈顶*/
Attempt crtatt;
stk[++top] = firtattp;
while (top != -1)
{
if (stk[top].state == 0 && stk[top].num > 1) /*当左边的节点还未访问时*/
{
stk[top].state = 1;
crtatt.src = stk[top].src;
crtatt.dst = OTHER(stk[top].src,stk[top].dst);
crtatt.num = stk[top].num-1;
crtatt.state = 0;
stk[++top] = crtatt; /*入栈*/
}else if (stk[top].state == 1){/*右边的节点还未访问时*/
move(stk[top].src,stk[top].dst);
crtatt.src = OTHER(stk[top].src, stk[top].dst);
crtatt.dst = stk[top].dst;
crtatt.num = stk[top].num-1;
crtatt.state = 0;
top--; /*出栈*/
stk[++top] = crtatt; /*入栈*/
}else if (stk[top].num <= 1){
move(stk[top].src, stk[top].dst);
top--;
}
}
}
int main()
{
printf("*******recurse solution**********\n");
recursHanoi(A, C,5);
printf("*******none-recurse solution**********\n");
norecurseHanoi(A, C, 5);
return 0;
}
hanoi塔的递归以及非递归函数
最新推荐文章于 2024-02-15 18:52:20 发布