【无标题】

汉诺塔(函数与递归) :

分三步走:

1.把A上(n-1)的dishes通过C移到B

2.把A上的最后1个dish移到C

3.把B上的(n-1)的dishes通过A移到C

三个dishes需要移动(2**3 -1)次

四个dishes需要移动(2**4-1)次

所以,n个dishes需要移动(2**n-1)次

第一次想可以以三个dishes为例 :

通过三个形参pos1,pos2,pos3 代表从...中转...移到... ;实现递归;

具体代码如下 :

#include<stdio.h>

void move(char x,char y)
{
    printf(" % c--> % c", x, y);
}

void hanoi(int n, char pos_1, char pos_2, char pos_3)
{
    if (n == 1)
    {
        move(pos_1, pos_3);
    }
    else
    {
        hanoi(n - 1, pos_1, pos_3, pos_2);
        move(pos_1, pos_3);
        hanoi(n - 1, pos_2, pos_1, pos_3);

    }
}
int main()
{
    hanoi(4, 'A', 'B', 'C');
    printf("\n");

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值