【发布时间】: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 上的很多例子。 所以,问题是:任何像这样的解决方案(我在网上找到的)是否真的包含错误或者我对递归的理解是错误的?
【问题讨论】:
-
问题是什么?您从解决方案中注释掉了一行,这使它成为错误的解决方案。