汉诺塔递归

参考视频:

 https://b23.tv/JtdNggX

代码 :

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

//pos1 起始位置
//pos2 中转位置
//pos3 目的位置
void hanoi(int n, char pos1, char pos2, char pos3)
{
	if (n == 1)
	{
		move(pos1, pos3);
	}
	else
	{
		hanoi(n - 1, pos1, pos3, pos2);//将 起始位置 的n-1个盘子借助 中转位置 移动到 目标位置
		move(pos1, pos3);//将起始位置上 最后一个 盘子移向目标位置
		hanoi(n - 1, pos2, pos1, pos3);//将 中转位置 的n-1个盘子借助 起始位置 移动到目标位置
	}
}
//move中的实参与hanoi函数中的形参相对应,而hanoi函数中形参a,b,c所对应的值也是在有规律的变化
int main()
{
	int n = 0;
	scanf("%d", &n);
	hanoi(n, 'A', 'B', 'C');
	return 0;
}

 分析图:

图不清晰,放个链接

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值