汉诺塔c语言代码
以下是一个使用C语言实现汉诺塔问题的代码:
#include<stdio.h>
void hanoi(int n, char from, char to, char aux) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
hanoi(n-1, from, aux, to);
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n-1, aux, to, from);
}
int main() {
int num_disks;
printf("Enter the number of disks: ");
scanf("%d", &num_disks);
printf("Steps to solve the Tower of Hanoi problem:\n");
hanoi(num_disks, 'A', 'C', 'B');
return 0;
}
这个代码中使用了递归的方法来解决汉诺塔问题。hanoi函数接受四个参数,分别是要移动的盘子数量n,起始柱子from,目标柱子to和辅助柱子aux。当n为1时,直接将盘子从起始柱子移动到目标柱子。否则,先将n-1个盘子从起始柱子移动到辅助柱子,然后将第n个盘子从起始柱子移动到目标柱子,最后将n-1个盘子从辅助柱子移动到目标柱子。主函数中读取用户输入的盘子数量,并调用hanoi函数来解决问题
原文地址: https://www.cveoy.top/t/topic/hAI2 著作权归作者所有。请勿转载和采集!