Java函数实现汉诺塔问题的递归算法
发布时间:2023-06-17 12:56:51
汉诺塔问题是一道经典的递归问题,目的是将一堆盘子从一个柱子移动到另一个柱子,要求在移动过程中,不能将一个大盘子放在一个小盘子上面。这里我们将汉诺塔问题的实现作为Java函数来写,函数的输入参数包括起始柱子、目标柱子和中转柱子的编号,以及需要移动的盘子数目。
首先,我们需要定义基础情况,当只有一个盘子时,我们只需要将其从起始柱子移动到目标柱子即可,函数实现如下:
public static void move(int n, int start, int target) {
System.out.println("Move plate " + n + " from stick " + start + " to stick " + target);
}
接下来,对于n个盘子的移动,我们需要将其分为两个操作:(1)将1到n-1号盘子从起始柱子移动到中转柱子;(2)将n号盘子从起始柱子移动到目标柱子;(3)将1到n-1号盘子从中转柱子移动到目标柱子。这里需要注意的是,过程中需要不断交换起始柱子、目标柱子和中转柱子的角色,以实现移动操作。我们用递归函数来实现上述三个操作,具体实现如下:
public static void hanoi(int n, int start, int target, int temp) {
if (n == 1) {
move(n, start, target);
} else {
hanoi(n - 1, start, temp, target);
move(n, start, target);
hanoi(n - 1, temp, target, start);
}
}
这里,hanoi函数接受四个参数:n表示需要移动的盘子数目,start表示起始柱子的编号,target表示目标柱子的编号,temp表示中转柱子的编号。当只有一个盘子时,直接调用move函数移动即可;对于n个盘子的情况,首先将1到n-1号盘子从起始柱子移动到中转柱子(即递归调用hanoi函数),然后将n号盘子从起始柱子移动到目标柱子(即调用move函数),最后将1到n-1号盘子从中转柱子移动到目标柱子(同样递归调用hanoi函数)。递归终止条件是只有一个盘子需要移动。整个Hanoi塔问题的递归解法完成。
下面是完整的Java程序:
public class HanoiTower {
public static void main(String[] args) {
int n = 3;
hanoi(n, 1, 3, 2);
}
public static void move(int n, int start, int target) {
System.out.println("Move plate " + n + " from stick " + start + " to stick " + target);
}
public static void hanoi(int n, int start, int target, int temp) {
if (n == 1) {
move(n, start, target);
} else {
hanoi(n - 1, start, temp, target);
move(n, start, target);
hanoi(n - 1, temp, target, start);
}
}
}
输出结果为:
Move plate 1 from stick 1 to stick 3 Move plate 2 from stick 1 to stick 2 Move plate 1 from stick 3 to stick 2 Move plate 3 from stick 1 to stick 3 Move plate 1 from stick 2 to stick 1 Move plate 2 from stick 2 to stick 3 Move plate 1 from stick 1 to stick 3
整个过程符合Hanoi塔问题的规律。
