参见英文答案 > How does recursive algorithm work for Towers of Hanoi? 2个
目前我正在阅读道格拉斯·克罗克福德(Douglas Crockford)的书,而且河内功能的塔楼有点过头了.即使将日志记录到控制台,我也无法真正了解正在发生的事情.这是我添加的功能:
var hanoi = function (disc,src,aux,dst) {
console.log(disc);
console.log(src,dst);
if (disc > 0) {
hanoi(disc - 1,dst,aux);
console.log('Move disc ' + disc + ' from ' + src + ' to ' + dst);
hanoi(disc - 1,dst);
}
}
hanoi(3,'Src','Aux','Dst');
这导致以下结果:
3
Src Dst
2
Src Aux
1
Src Dst
0
Src Aux
Move disc 1 from Src to Dst
0
Aux Dst
Move disc 2 from Src to Aux
1
Dst Aux
0
Dst Src
Move disc 1 from Dst to Aux
0
Src Aux
Move disc 3 from Src to Dst
2
Aux Dst
1
Aux Src
0
Aux Dst
Move disc 1 from Aux to Src
0
Dst Src
Move disc 2 from Aux to Dst
1
Src Dst
0
Src Aux
Move disc 1 from Src to Dst
0
Aux Dst
而且我很早就输了.在结果的第6行,它怎么能从Src Aux回到Src Dst?
最佳答案
原文链接:https://www.f2er.com/js/429754.html