【递归】汉诺塔的递归与非递归(压栈)

递归方法很多很多了;

c语言汉诺塔hanoi问题非递归方法--压栈:

#include <stdio.h>

struct stack
{
    int n;
    char x, y, z;
}sta[200];



void hanoi(int n, char a, char b, char c);
void hanoiStack(int n, char fr, char to, char by);

int main(void)
{
    int n;
    printf("How many hanoi TOWERS?\n");
    
    for(int loop = 0; loop < 200; loop++)
    {
        sta[loop].n = 0;
        sta[loop].x = '0';
        sta[loop].y = '0';
        sta[loop].z = '0';
    }
    
    scanf("%d", &n);
    hanoiStack(n, 'a', 'b', 'c');
    return 0;
}
void hanoi(int n, char a, char b, char c)
{
    if(n == 1)
        printf("%c --> %c\n", a, c);
    else
    {
        hanoi(n - 1, a, c, b);
        printf("%c --> %c\n", a, c);
        hanoi(n - 1, b, a, c);
    }
}
void hanoiStack(int n, char fr, char to, char by)
{
    int top = -1, n1, a, b, c;

    top++;
    sta[top].n = n; 
    sta[top].x = fr; 
    sta[top].y = to; 
    sta[top].z = by;

    while(top > -1)
    {
        n1 = sta[top].n;
        a = sta[top].x;
        b = sta[top].y;
        c = sta[top].z;
        top--;
        
        // 下面压栈
        if(n1 > 1)
        {
            top++;
            sta[top].n = n1 - 1;
            sta[top].x = b;
            sta[top].y = a;
            sta[top].z = c;
            
            top++;
            sta[top].n = 1;
            sta[top].x = a;
            sta[top].z = c;
            
            top++;
            sta[top].n = n1 - 1;
            sta[top].x = a;
            sta[top].y = c;
            sta[top].z = b;

        }
        else
        {
            printf("\nmove from %c to %c ", a, c);
        }
    }
}

 

此方法还有一点小问题。

过程类似于:https://blog.csdn.net/weixin_37817685/article/details/78649373

解说2:https://wenku.baidu.com/view/a899321253d380eb6294dd88d0d233d4b14e3fa2.html

转载于:https://www.cnblogs.com/paprikatree/p/10462710.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值