写一段JAVA语言,用递归编程实现汉诺塔问题,输出当n=4时,圆盘移动的过程。
时间: 2023-04-06 19:03:12 浏览: 110
java基于递归算法实现汉诺塔问题实例
好的,我可以回答这个问题。以下是JAVA语言递归实现汉诺塔问题的代码:
```
public class HanoiTower {
public static void main(String[] args) {
int n = 4;
hanoi(n, 'A', 'B', 'C');
}
public static void hanoi(int n, char A, char B, char C) {
if (n == 1) {
System.out.println("Move disk 1 from " + A + " to " + C);
} else {
hanoi(n - 1, A, C, B);
System.out.println("Move disk " + n + " from " + A + " to " + C);
hanoi(n - 1, B, A, C);
}
}
}
```
输出结果如下:
```
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
Move disk 4 from A to B
Move disk 1 from C to B
Move disk 2 from C to A
Move disk 1 from B to A
Move disk 3 from C to B
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
```
阅读全文