基于C语言用递归算法实现汉诺塔解法的计算

基于C语言用递归算法实现汉诺塔解法的计算
如有不懂欢迎提问

#include<stdio.h>

int steps = 0;

//三根柱A(用0表示),B(用1表示),C(用2表示),起始A,目标C

void print(int num, int get, int put) {
	steps++;
	printf("move disk%3d from %c to %c\n", num, get == 0 ? 'A' : get == 1 ? 'B' : 'C', put == 0 ? 'A' : put == 1 ? 'B' : 'C');
}
void mv(int num,int a,int b,int c) {
	if (num == 1)
		print(1, a, c);
	else {
		mv(num - 1, a, c, b);
		print(num, a, c);
		mv(num - 1, b, a, c);
	}
}
int main() {
	int n;
	printf("Input the number of disks:");
	scanf("%d", &n);
	printf("The setps to moving %3d disks:\n",n);
	mv(n, 0, 1, 2);
	printf("Complelt in %d steps!\n",steps);
	return 0;
}

在这里插入图片描述

交流讨论等具体内容请访问我的博客

原文地址:https://boyinthesun.cn/post/c-hanoi/

发布了16 篇原创文章 · 获赞 0 · 访问量 133

猜你喜欢

转载自blog.csdn.net/weixin_37891983/article/details/105229798