Java编写程序实现汉诺塔,用户输入盘子个数,输出盘子移动的信息
时间: 2024-05-04 13:15:40 浏览: 13
好的,这是一个经典的递归问题,以下是Java代码实现汉诺塔问题:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入盘子个数:");
int n = sc.nextInt();
hanoi(n, 'A', 'B', 'C');
}
public static void hanoi(int n, char A, char B, char C) {
if (n == 1) {
System.out.println("将第1个盘子从" + A + "移到" + C);
} else {
hanoi(n - 1, A, C, B);
System.out.println("将第" + n + "个盘子从" + A + "移到" + C);
hanoi(n - 1, B, A, C);
}
}
}
```
输入盘子个数后,程序会输出盘子移动的信息。希望能帮到你!
相关问题
编写程序实现汉诺塔,用户输入盘子个数,输出盘子移动的信息
好的,这个问题很有趣!以下是汉诺塔的程序实现:
```
def hanoi(n, source, target, auxiliary):
if n == 1:
print("Move disk 1 from source", source, "to target", target)
return
hanoi(n-1, source, auxiliary, target)
print("Move disk", n, "from source", source, "to target", target)
hanoi(n-1, auxiliary, target, source)
n = int(input("Enter number of disks: "))
hanoi(n, 'A', 'C', 'B')
```
这个程序会要求用户输入盘子的个数,然后输出每一步移动的信息,实现汉诺塔的移动。希望这个程序对你有帮助!
用python编写程序,实现输出汉诺塔移动过程的功能
下面是一个 Python 程序,可以输出汉诺塔的移动过程:
```python
def hanoi(n, source, target, auxiliary):
if n == 1:
print("Move disk 1 from", source, "to", target)
return
hanoi(n-1, source, auxiliary, target)
print("Move disk", n, "from", source, "to", target)
hanoi(n-1, auxiliary, target, source)
# 测试程序
n = 3
hanoi(n, 'A', 'C', 'B')
```
输出:
```
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
```
在这个程序中,我们定义了一个函数 `hanoi()`,用于输出汉诺塔的移动过程。这个函数接受四个参数:`n` 表示盘子的数量,`source` 表示初始位置,`target` 表示目标位置,`auxiliary` 表示辅助位置。函数内部递归调用自己,实现汉诺塔的移动过程。最后我们测试程序,输入盘子数量为 3,初始位置为 A,目标位置为 C,辅助位置为 B。程序会输出汉诺塔的移动过程。