【问题标题】:Hanoi Tower recursion solution error河内塔递归解决错误
【发布时间】:2016-01-27 22:35:09
【问题描述】:

教授向我们展示了河内塔问题的递归解决方案:

public class Hanoi {

   static Stack<Integer> from;
   static Stack<Integer> temp;
   static Stack<Integer> to;

   public static void print() {
         System.out.println("------------------------");
         System.out.println(" FIRST " + from.toString());
         System.out.println("SECOND " + temp.toString());
         System.out.println(" THIRD " + to.toString());
   }

   public static void move(Stack<Integer> from, Stack<Integer> to) {
         to.push(from.pop());
         print();
   }

   public static void invokeHanoiLogic(Stack<Integer> first, Stack<Integer> second, Stack<Integer> third, int quantity) {

         if(quantity > 0) {
                invokeHanoiLogic(first, third, second, quantity - 1);

                move(first, third);

                invokeHanoiLogic(second, first, third, quantity - 1);
         }

   }

   public static void main(String[] args) {
         from = new Stack<>();
         temp = new Stack<>();
         to = new Stack<>();

         from.push(3);
         from.push(2);
         from.push(1);

         invokeHanoiLogic(from, temp, to, from.size());
   }

}

但是如果我们注释第三个字符串 // invokeHanoiLogic(second, first, third, quantity - 1);检查第一个递归深度结果:

             if(quantity > 0) {
                invokeHanoiLogic(first, third, second, quantity - 1);

                move(first, third);

                //invokeHanoiLogic(second, first, third, quantity - 1);
         }

我在控制台日志中发现错误:

 ------------------------
FIRST [5, 4, 3, 2]
SECOND []
THIRD [1]
------------------------
FIRST [5, 4, 3]
SECOND [2]
THIRD [1]
------------------------
FIRST [5, 4]
SECOND [2]
THIRD [1, 3]
------------------------
FIRST [5]
SECOND [2, 4]
THIRD [1, 3]
------------------------
FIRST []
SECOND [2, 4]
THIRD [1, 3, 5]

但是这个解决方案对应于 web 上的很多例子。 所以,问题是:任何像这样的解决方案(我在网上找到的)是否真的包含错误或者我对递归的理解是错误的?

【问题讨论】:

  • 问题是什么?您从解决方案中注释掉了一行,这使它成为错误的解决方案。

标签: java recursion


【解决方案1】:

有意义的是,如果您注释掉工作算法的一部分,它将停止工作。

河内塔的(正确)递归实现的想法是,如果您必须将 n 个元素从第一个塔移动到第三个塔,您首先递归地将元素 n-1 到 1 移动到第二个塔,然后将第 n 个元素移动到第三个塔,最后递归地将元素 n-1 移动到 1 到第三个塔。如果你跳过第二个递归调用,它根本不起作用。

【讨论】:

  • 但是,如果我没记错的话,首先方法 invokeHanoiLogic 必须从第一个递归深度执行操作:invokeHanoiLogic(first, third, second, quantity - 1);移动(第一,第三);然后第二个递归深度invokeHanoiLogic(second, first, third, quantity - 1); .所以,第一次递归迭代没有达到 Hanoi 规则。
  • @Andrew 我不明白你的意思。
  • 我的意思是一开始,当程序到达那一行时-invokeHanoiLogic(first,third,second,quantity-1);它越来越深,直到(数量> 0)然后它必须执行行 - 移动(第一,第三);在每个递归调用中,它必须执行行 invokeHanoiLogic(second, first, third, quantity - 1);如果我的递归理解是正确的:在程序到达行之前 invokeHanoiLogic(second, first, third, quantity - 1); ,程序执行错误的操作。
  • 它执行的正是它应该做的,注意函数调用(第三,第二)。在每个递归级别上切换极点 2 和 3。
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 2015-10-08
  • 2014-05-31
相关资源
最近更新 更多