用c语言利用递归写一个汉诺塔游戏
时间: 2024-06-03 12:08:19 浏览: 147
#include <stdio.h>
void hanoi(int n, char from, char to, char temp) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
hanoi(n-1, from, temp, to);
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n-1, temp, to, from);
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
hanoi(n, 'A', 'C', 'B');
return 0;
}
相关问题
用c语言实现利用递归写一个汉诺塔的游戏
```c
#include <stdio.h>
void hanoi(int n, char A, char B, char C) {
if (n == 1) {
printf("%c -> %c\n", A, C);
return;
}
hanoi(n - 1, A, C, B);
printf("%c -> %c\n", A, C);
hanoi(n - 1, B, A, C);
}
int main() {
int n;
printf("请输入汉诺塔的层数:");
scanf("%d", &n);
hanoi(n, 'A', 'B', 'C');
return 0;
}
```
输入汉诺塔的层数后,程序会输出每一步移动的过程。例如输入3,则输出:
```
A -> C
A -> B
C -> B
A -> C
B -> A
B -> C
A -> C
```
利用递归写一个汉诺塔的游戏。用C语言写
#include <stdio.h>
void hanoi(int n, char from, char to, char via) {
if (n == 1) {
printf("Move disk 1 from %c to %c\n", from, to);
return;
}
hanoi(n-1, from, via, to);
printf("Move disk %d from %c to %c\n", n, from, to);
hanoi(n-1, via, to, from);
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
hanoi(n, 'A', 'C', 'B');
return 0;
}
阅读全文