将马随机放在国际象棋的8*8棋盘的某个方格中,马按走棋规则进行移动。要求每个方格上只进入一次,走遍棋盘上全部64个方格。编制非递归程序,求出马的行走路线,并按求出的行走路线,将数字1,2,…,64依次填入一个8*8的方阵,输出之。
时间: 2024-06-09 17:06:29 浏览: 157
这里给出一个非递归的深度优先搜索算法,使用栈来模拟递归过程:
```python
class Pos:
def __init__(self, x, y):
self.x = x
self.y = y
def knight_tour():
board = [[0]*8 for _ in range(8)]
moves = [(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)]
stack = [Pos(0, 0)]
board[0][0] = 1
idx = 2
while len(stack) > 0:
pos = stack[-1]
found = False
for move in moves:
next_pos = Pos(pos.x + move[0], pos.y + move[1])
if next_pos.x < 0 or next_pos.x > 7 or next_pos.y < 0 or next_pos.y > 7:
continue
if board[next_pos.x][next_pos.y] == 0:
stack.append(next_pos)
board[next_pos.x][next_pos.y] = idx
idx += 1
found = True
break
if not found:
board[pos.x][pos.y] = 0
stack.pop()
idx -= 1
for row in board:
print(row)
```
运行该函数即可得到马的行走路线并填入方阵中。
阅读全文