C语言编程实现汉诺塔问题,要求输出碟子的移动过程和移动次数
时间: 2024-05-03 08:20:44 浏览: 86
好的,这是一个经典的递归问题。以下是实现汉诺塔问题的 C 代码:
```
#include <stdio.h>
void move(int n, char source, char target, char helper, int* count){
if(n == 1){
(*count)++;
printf("%d. Move disk 1 from %c to %c\n", *count, source, target);
return;
}
move(n-1, source, helper, target, count);
(*count)++;
printf("%d. Move disk %d from %c to %c\n", *count, n, source, target);
move(n-1, helper, target, source, count);
}
int main(){
int num, count = 0;
printf("Enter the number of disks: ");
scanf("%d", &num);
move(num, 'A', 'C', 'B', &count);
printf("Total moves: %d\n", count);
return 0;
}
```
当执行上述代码并输入3时,输出结果为:
```
Enter the number of disks: 3
1. Move disk 1 from A to C
2. Move disk 2 from A to B
3. Move disk 1 from C to B
4. Move disk 3 from A to C
5. Move disk 1 from B to A
6. Move disk 2 from B to C
7. Move disk 1 from A to C
Total moves: 7
```
如上所示,程序成功地实现了汉诺塔问题,并输出了移动次数及具体的移动过程。
阅读全文