python汉诺塔不用递归只用循环编程代码
时间: 2023-12-27 18:00:24 浏览: 73
汉诺塔问题是经典的递归应用,但也可以使用循环来解决。以下是Python编程代码:
```python
def hanoi(n, start, end, aux):
if n % 2 == 0:
end, aux = aux, end
pegs = [list(range(n, 0, -1)), [], []]
actions = [[0, 1], [0, 2], [1, 2]]
for i in range(2 ** n - 1):
peg, action = next(((peg, action) for peg, action in enumerate(actions) if pegs[action[0]] and (not pegs[action[1]] or pegs[action[0]][-1] < pegs[action[1]][-1])), (None, None))
pegs[action[1]].append(pegs[action[0]].pop())
if action == [start, end]:
print(f"Move disk from peg {start} to peg {end}")
else:
print(f"Move disk from peg {action[0]} to peg {action[1]}")
hanoi(3, 0, 2, 1)
```
这个循环解法思路是使用一个额外的辅助数组来记录每一个步骤,利用循环不断更新辅助数组中的值,直到所有的盘子都被移动到目标柱子上。
阅读全文