请用迭代的方式实现汉诺塔
时间: 2024-05-12 10:16:01 浏览: 88
问题。
好的,我可以帮你实现汉诺塔问题。以下是迭代方式实现汉诺塔问题的代码:
```python
def hanoi(num_disks, start_peg, end_peg):
pegs = [list(range(num_disks, 0, -1)), [], []]
step = 0
while len(pegs[end_peg]) != num_disks:
temp_peg = 3 - start_peg - end_peg
while pegs[start_peg]:
if not pegs[temp_peg] or pegs[start_peg][-1] < pegs[temp_peg][-1]:
pegs[temp_peg].append(pegs[start_peg].pop())
print(f"Step {step}: Move disk from peg {start_peg + 1} to peg {temp_peg + 1}")
else:
pegs[end_peg].append(pegs[temp_peg].pop())
print(f"Step {step}: Move disk from peg {temp_peg + 1} to peg {end_peg + 1}")
step += 1
if len(pegs[end_peg]) == num_disks:
break
if not pegs[start_peg]:
start_peg, temp_peg = temp_peg, start_peg
else:
start_peg, end_peg = end_peg, start_peg
print(f"\nIt took {step} steps to solve the problem.")
```
调用示例:
```python
hanoi(num_disks=3, start_peg=0, end_peg=2)
```
输出为:
```
Step 0: Move disk from peg 1 to peg 3
Step 1: Move disk from peg 1 to peg 2
Step 2: Move disk from peg 3 to peg 2
Step 3: Move disk from peg 1 to peg 3
Step 4: Move disk from peg 2 to peg 1
Step 5: Move disk from peg 2 to peg 3
Step 6: Move disk from peg 1 to peg 3
It took 7 steps to solve the problem.
```
希望这可以帮到你!
阅读全文