汉诺塔问题 java 解法
时间: 2023-10-11 07:21:54 浏览: 88
以下是汉诺塔问题的Java递归解法:
```java
public class HanoiTower {
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);
}
}
public static void main(String[] args) {
int n = 3; // 盘子的个数
hanoi(n, 'A', 'B', '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
```
其中,n为盘子的个数,A、B、C分别表示三个柱子。在hanoi函数中,如果只有一个盘子,直接将它从A柱子移动到C柱子;否则,先将n-1个盘子从A柱子移动到B柱子,再将第n个盘子从A柱子移动到C柱子,最后将n-1个盘子从B柱子移动到C柱子。
阅读全文