注意:我理解递归解决方案; 但我不知道代码是如何实现的,因为我无法按照代码执行的步骤进行操作.
我很难理解河内塔的递归循环.我已经评论并尝试了各种策略来了解程序是如何运作的,但我似乎无法掌握循环如何运作以及环如何被引导.
def move(rings, from, destination, other)
if rings == 1
ring = from.pop
p "Move ring #{ring} from #{from} to #{destination}"
destination.push ring
else
move(rings-1, from, other, destination)
move(1, from, destination, other)
move(rings-1, other, destination, from)
end
end
Run Code Online (Sandbox Code Playgroud)
这是输出:
"Move ring 1 from a to c"
"Move ring 2 from a to b"
"Move ring 1 from c to b"
"Move ring 3 from a to c"
"Move ring 1 from b to a"
"Move ring 2 from …
Run Code Online (Sandbox Code Playgroud)