hanoi塔的递归以及非递归函数

/**
 * @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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值