汉诺塔c语言程序代码打印每一步并计算总步数
时间: 2024-09-15 11:12:30 浏览: 38
汉诺塔是一个经典的递归问题,涉及到三个柱子和一些大小不同的圆盘。目标是从第一个柱子将所有盘子移动到第三个柱子,但每次只能移动一个大盘子,并且任何时候都不能有大盘子放在小盘子上面。这里是一个简单的C语言程序,实现了汉诺塔的步骤打印和步数计算:
```c
#include <stdio.h>
void hanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);
} else {
// Move top n-1 disks from source to auxiliary rod
hanoi(n - 1, from_rod, aux_rod, to_rod);
// Move the nth disk from source to target rod
printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);
// Move the n-1 disks from auxiliary to target rod
hanoi(n - 1, aux_rod, to_rod, from_rod);
}
}
int main() {
int num_disks; // Number of disks
printf("Enter the number of disks: ");
scanf("%d", &num_disks);
// Calculate and print the total steps for the given number of disks
int total_steps = pow(2, num_disks) - 1;
printf("Total steps needed: %d\n", total_steps);
hanoi(num_disks, 'A', 'C', 'B'); // A is source, C is destination, B is auxiliary
return 0;
}
```
当你运行这个程序时,它会提示输入盘子的数量,然后按照汉诺塔规则一步步地移动,同时在控制台打印出每一步的操作。最后,它还会计算并输出完成整个游戏所需的总步数。
阅读全文