汉诺塔 - JavaScript的 - 好的部分 [英] Tower Of Hanoi - JavaScript - THe Good Parts
问题描述
我见过的其他问题上的SO关于递归函数,我已经阅读了反应,但我还是不能让算法来点击我的头
I have seen the other Questions on SO about the Recursive function and I have read the responses but I still can't get the algorithm to click in my head
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得到运行机会呢?
How does the document.write(...), ever run. My Logic is First time we run the function disc is > 3. then we recursively call the function again skipping everything below so how does the document.write get a chance to run?
据我了解递归(做了基本的例子),但我还是不能看你怎么得到的输出。如果有一种方法,我可以运行它直观地看到它在行动,这将有助于很多。
I understand recursion (done the basic examples) but i still can't see how you get an output. If there is a way i can run it visually and see it in action, that would help alot.
推荐答案
您能想到的会发生什么事是调用树(从上一次移动到下):
You can think of what will happen as a call tree (time moves from top to bottom):
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]
这篇关于汉诺塔 - JavaScript的 - 好的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!