求总步数:
由:F(n)= 2F(n-1)+1
得:F(n) = 2^n - 1
步骤实现:
js
const haonoi = (n, from, ass, to) => {
if (n > 0) {
haonoi(n - 1, from, to, ass);
move(n, from, to);
haonoi(n - 1, ass, from, to);
}
}
const move = (n, from, to) => {
console.log('移动第 ' + n + ' 个从 ' + from + ' 到 ' + to);
}
//调用
haonoi(5, 'A', 'B', 'C')
python
def hanoi(n, a, b, c):
if n == 1:
print(a, '-->', c)
else:
hanoi(n - 1, a, c, b)
print(a, '-->', c)
hanoi(n - 1, b, a, c)
# 调用
hanoi(5, 'A', 'B', 'C')
网友评论