汉诺塔真是学递归的经典例子啊~这里再来一个 Ruby 版本的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@step_nbr = 0

def hanoi(height, from_pole, to_pole, with_pole)
if height >= 1
hanoi(height - 1, from_pole, with_pole, to_pole)
@step_nbr += 1
puts "#{@step_nbr}: move disk from #{from_pole} to #{to_pole}"
hanoi(height - 1, with_pole, from_pole, to_pole)
end
end

puts 'Please enter the height of the tower:'
height = gets
hanoi(height.to_i, 'a', 'b', 'c')

留言

2014-05-08