汉诺塔问题:有若干大小不一的石盘按照从小到大顺序叠在A塔座上,借助B塔座将所有石盘移到C, 每次只允许移动一个石盘,且始终保持小盘在上,大盘在下,请问要移动多少次? 递归函数解决

#include<stdio.h>

int hanno(int n,char one, char two, char three)/*括号中形参的意思是,借助two将n个
											   石盘从one上移动到three上,所以写程序的
											   时候不要太死板了,好吗。本题值得再三
											   的看和体会*/
{
	static int num = 0;
	void movet(char x, char y);//当函数在下方定义时,记得在使用它的函数中声明一下
	if (n == 1)
	{
		movet(one, three);
		num++;
	}
	else
	{
		hanno(n - 1, one, three, two);
		movet(one, three);
		num++;
		hanno(n - 1, two, one, three);
	}
	return num;
}
void movet(char x, char y)//one上只有一个时,这是最终操作
{
	printf("%c->%c\n", x, y);
}
void main()
{
	char one = 'A', two = 'B', three = 'C';
	int n;
	int num;
	printf("请输入石盘个数:");
	scanf_s("%d", &n);
	num=hanno(n,one,two,three);
	printf("一共移动%d次\n", num);

	getchar();
	getchar();
}

运行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值