编写JAVA程序演示汉诺塔游戏步骤(3个圆盘),效果如下: 1: move 1 from A to C. 2: move 2 from A to B. 3: move 1 from C to B. 4: move 3 from A to C. 5: move 1 from B to A. 6: move 2 from B to C. 7: move 1 from A to C.
时间: 2023-04-05 15:01:54 浏览: 154
以下是JAVA程序演示汉诺塔游戏步骤(3个圆盘)的代码:
public class HanoiTower {
public static void main(String[] args) {
int n = 3;
hanoi(n, 'A', 'B', 'C');
}
public static void hanoi(int n, char A, char B, char C) {
if (n == 1) {
System.out.println("move 1 from " + A + " to " + C);
} else {
hanoi(n - 1, A, C, B);
System.out.println("move " + n + " from " + A + " to " + C);
hanoi(n - 1, B, A, C);
}
}
}
输出结果为:
move 1 from A to C
move 2 from A to B
move 1 from C to B
move 3 from A to C
move 1 from B to A
move 2 from B to C
move 1 from A to C
相关问题
3. 编写程序演示汉诺塔游戏步骤(3个圆盘),效果如下: 1: move 1 from A to C. 2: move 2 from A to B. 3: move 1 from C to B. 4: move 3 from A to C. 5: move 1 from B to A. 6: move 2 from B to C. 7: move 1 from A to C.
以下是汉诺塔游戏的步骤演示:
#include <stdio.h>
void hanoi(int n, char A, char B, char C) {
if (n == 1) {
printf("move 1 from %c to %c.\n", A, C);
} else {
hanoi(n-1, A, C, B);
printf("move %d from %c to %c.\n", n, A, C);
hanoi(n-1, B, A, C);
}
}
int main() {
int n = 3;
hanoi(n, 'A', 'B', 'C');
return ;
}
输出结果如下:
move 1 from A to C.
move 2 from A to B.
move 1 from C to B.
move 3 from A to C.
move 1 from B to A.
move 2 from B to C.
move 1 from A to C.
编写程序演示汉诺塔游戏步骤(3个圆盘),效果如下: 1: move 1 from A to C. 2: move 2 from A to B. 3: move 1 from C to B. 4: move 3 from A to C. 5: move 1 from B to A. 6: move 2 from B to C. 7: move 1 from A to C.
以下是汉诺塔游戏的 C 语言程序,可以演示 3 个圆盘的步骤:
#include <stdio.h>
void hanoi(int n, char A, char B, char C) {
if (n == 1) {
printf("move 1 from %c to %c.\n", A, C);
} else {
hanoi(n-1, A, C, B);
printf("move %d from %c to %c.\n", n, A, C);
hanoi(n-1, B, A, C);
}
}
int main() {
hanoi(3, 'A', 'B', 'C');
return 0;
}
阅读全文