【问题标题】:Tower Of Hanoi - JavaScript - THe Good Parts [duplicate]河内塔 - JavaScript - 好的部分 [重复]
【发布时间】:2013-10-19 04:59:09
【问题描述】:

我已经看到关于递归函数的其他问题,并且我已经阅读了回复,但我仍然无法让算法在我的脑海中点击

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(...) 是如何运行的。我的逻辑是我们第一次运行函数 disc is > 3。然后我们再次递归调用该函数,跳过下面的所有内容,那么 document.write 如何获得运行的机会?

我了解递归(完成了基本示例),但我仍然看不到您如何获得输出。如果有一种方法可以让我直观地运行它并查看它的实际效果,那将有很大帮助。

【问题讨论】:

    标签: javascript algorithm recursion


    【解决方案1】:

    你可以把会发生的事情想象成一个调用树(时间从上到下移动):

    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]
    

    【讨论】:

    • +1 我正要写同样的东西,但你的更具可读性。我认为,关键是不要将每个hanoi() 视为GOTO,而是将其视为前一个hanoi() 的子程序。从这个意义上说,它确实有 disc 变为 0,但它仍然有三个 hanois 打开,它们将继续运行。 “安妮要在鲍勃离开后离开,在辛迪离开后谁离开,在道格离开后谁离开”之类的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多