河内塔- JavaScript -好的部分

Tower Of Hanoi - JavaScript - THe Good Parts

本文关键字:JavaScript 内塔      更新时间:2023-09-26

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

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。然后我们再次递归地调用函数跳过下面的所有内容,那么文档如何。写有机会跑吗?

我理解递归(做了基本的例子),但我仍然看不出你是如何得到输出的。如果有一种方法,我可以运行它的视觉和看到它在行动,这将帮助很大。

你可以把它想象成一个调用树(时间从上到下移动):

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]