河内塔,工作,但不应该

时间:2014-04-06 21:30:49

标签: java recursion towers-of-hanoi

所以我们有经典的河内问题,我只是进入这个递归的东西,它是一个doozie! 这是完全正常运作,但我只是不明白它是怎么回事!正如我所理解的那样,对于任何n,它将打印“from +”到“+ thru”,这将发生在每次n接近1时。人们会认为在n = 1时,代码会停止,然而我得到“通过+”的打印输出到“+到”(最后打印输出)。如果n = 1是终止条件,我怎么可能“免费获得”最后一部分代码?

我还期望AT LEAST的代码在每次迭代时执行最后一次打印输出,但不是!此外,这个例子总是包括两个递归调用,但这只适用于一个!这到底是怎么回事?这段代码是如何逐步执行的?我是否误解了递归方法的一些基本事实? (在Eclipse编译器上编译)。

 public static void hanoi(char from, char to, char thru, int n) {
if (n==1) {
  System.out.println(from + " going to " + to);
}  else {
  System.out.println (from + " going to " + thru);
  hanoi(from, to, thru, n-1);
  System.out.println (thru + " going to " + to);
}
  }

3 个答案:

答案 0 :(得分:0)

  

我是否误解了一些关于递归方法的基本事实?

听起来像你有。您似乎有这样的印象:即使您多次调用该方法,该方法也只退出一次。事实上,每当你点击这一行:

System.out.println (from + " going to " + thru); <-- this line
hanoi(from, to, thru, n-1);
System.out.println (thru + " going to " + to);

...在递归调用完成后,您还必须在某个时刻点击后一行:

System.out.println (from + " going to " + thru);
hanoi(from, to, thru, n-1);
System.out.println (thru + " going to " + to);   <-- this line

n == 1是“终止条件”,因为它不会进行额外的递归调用。但是,您的“if”语句仍然包含代码:

if (n==1) {
  System.out.println(from + " going to " + to);
}

此代码将作为最终条件的一部分运行,但不会再次调用hanoi方法。但是,这只是递归调用的结束。对于在此之前调用hanoi的每个时间,堆栈上仍然存在方法调用,并且需要完成这些方法调用。

  System.out.println (from + " going to " + thru);
  hanoi(from, to, thru, n-1);   <-- if `n-1` here was `1`, you'd still have to 
                                    complete the following line.
  System.out.println (thru + " going to " + to);

答案 1 :(得分:0)

  

有人会认为在n = 1时,代码会停止

这是错误的假设所在。守则不会停止。执行后 System.out.println(from + " going to " + to); 该方法返回到调用它的位置。在你的情况下。这就是调用hanoi(from, to, thru, n-1);的地方。 然后它一直持续到方法结束,因此执行System.out.println (thru + " going to " + to); 然后它再次返回到它的调用位置,并再次继续,直到方法体的结尾。这种情况会一次又一次地发生,直到您第一次拨打hanoi()

答案 2 :(得分:0)

河内的目标是带来来自&#34;的所有作品。到&#34;到&#34;,听起来有点傻,所以让我们来电话#34;来自&#34; &#34;左&#34;相反,&#34;到&#34; &#34;右&#34 ;.对于n = 1,您只需将棋子从左侧直接移动到右侧,即可按照其规则成功完成游戏。这就是你提到的文字显示原因。

对于n = 2,您必须将顶部件移动到中间,底部向右移动较大的部件,然后从中间向右移动较小的部件。

在伪代码中,其内容如下:

put the left piece to the middle

put the (other) left piece to the right 
(note that the roles of middle and right 
have been switched in the call of the 
hanoi-method and n is now 1, so no more calls)

put the middle piece to the right