用Java递归编程实现汉诺塔问题,输出当n=4时,圆盘移动的过程。
时间: 2023-04-02 10:05:02 浏览: 101
好的,我可以回答这个问题。以下是Java递归编程实现汉诺塔问题,输出当n=4时,圆盘移动的过程的代码:
```
public class HanoiTower {
public static void main(String[] args) {
int n = 4;
hanoi(n, 'A', 'B', 'C');
}
public static void hanoi(int n, char from, char temp, char to) {
if (n == 1) {
System.out.println("Move disk 1 from " + from + " to " + to);
} else {
hanoi(n - 1, from, to, temp);
System.out.println("Move disk " + n + " from " + from + " to " + to);
hanoi(n - 1, temp, from, to);
}
}
}
```
输出结果为:
```
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
```
阅读全文