java - 汉诺塔递归java

标签 java recursion

这是我使用递归解决汉诺塔问题的 Java 代码:

/**here is a stack of N disks on the first of three poles (call
them A, B and C) and your job is to move the disks from pole A to pole B without
ever putting a larger disk on top of a smaller disk.*/ 

public class Hanoi {

    public static void main(String[] args) {
        playHanoi (2,"A","B","C");
    }

    //move n disks from position "from" to "to" via "other"
    private static void playHanoi(int n, String from , String other, String to) {
        if (n == 0)
            return;
        if (n > 0)
        playHanoi(n-1, from, to, other);
        System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);
        playHanoi(n-1, other, from, to);
    }

}

我放置打印方法的地方重要吗?另外,我可以这样做吗:

    playHanoi(n-1, from, to, other);
    playHanoi(n-1, other, from, to);
    System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);

最佳答案

以这种方式解决 Tower of Hanoy 问题,只不过是定义了您希望如何完成工作的策略。还有你的代码:

    playHanoi(n-1, from, to, other);
    System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);
    playHanoi(n-1, other, from, to);

基本上将您的策略​​定义为如下所示,

  1. n-1 个磁盘从"from"(源塔)移动到“其他”(中间塔)。
  2. 然后将第 n 个磁盘从"from"(源塔)移动到“到”(目的地塔)。
  3. 最后将n-1 个磁盘从"other"(中间塔)移动到< strong>“到”(目的地塔)。

您的 prinf 基本上执行第 2 步。

现在如果你写这样的代码:

    playHanoi(n-1, from, to, other);
    playHanoi(n-1, other, from, to);
    System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);

那么你基本上是在做:

  1. n-1 个磁盘从"from"(源塔)移动到“其他”(中间塔)。

  2. 然后将 n-1 个磁盘从"other"(中间塔)移动到< em>“到”(目的地塔)。

  3. 最后将第 n 个磁盘从"from"(源塔)移动到“到”(目的地塔)。

    In this strategy, after doing the 2 nd step (moving all n-1 disks from "other" to "to"), 3 rd step becomes invalid(moving n th disk from "from" to "to")! Because in Tower of Hanoy you cant put a larger disk on a smaller one!

所以选择第二个选项(策略)会导致你的策略无效,这就是为什么你不能这样做!

关于java - 汉诺塔递归java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493511/

相关文章:

python - C++ 或 Python 中字符串所有排列的算法

c++ - 为什么在递归中使用循环会产生意想不到的结果?

javascript - 如何循环对象的javascript对象并查找属性

java - com.querydsl.core.Tuple 的 ClassCastException

java - 属性响应的规范强制值

java - 如何为具有特定注释的字段设置 FindBugs 过滤器?

recursion - 我如何阻止(和加入)由未知数量的 goroutines 提供的 channel ?

java - 检索给定搜索条件的字符串。括号、引号等

java - System.out.println 不打印输出

python - 列表中的所有 6 数排列