河内塔 - JavaScript - 很好的部分

时间:2011-08-15 01:48:04

标签: javascript algorithm recursion

我已经看过关于递归函数的其他问题,我已经阅读了回复,但我仍然无法让算法点击我的脑袋

var hanoi = function (disc, src, aux, dst) {

  if (disc > 0) {
    hanoi(disc - 1, src, dst, aux);
   document.write('Move disc ' + disc + ' from ' + src + ' to ' + dst);
    hanoi(disc - 1, aux, src, dst);
  }
}

hanoi(3, 'Src', 'Aux', 'Dst');

document.write(...)如何运行。我的逻辑是我们第一次运行功能光盘是> 3.然后我们递归调用函数再次跳过下面的所有内容,那么document.write如何有机会运行?

我理解递归(完成了基本的例子),但我仍然无法看到你如何获得输出。如果有一种方法,我可以直观地运行它并看到它在行动,这将有所帮助。

1 个答案:

答案 0 :(得分:22)

你可以想到作为一个调用树会发生什么(时间从上到下):

hanoi(3, ...) =>
 |-> hanoi(2, ...) =>
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |    |-> document.write(...)
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |  <-/ [hanoi(2, ...) finished]
 |-> document.write(...) [halfway done!]
 |-> hanoi(2, ...) =>
 |    \-> [same pattern as the first time, with different data]
 \-> [hanoi(3, ...) finished]
相关问题