此题求最短路径,用广度优先搜索(BFS)比较合适。
按照规则,对每个点来说跳马共有八个可能的下一跳落脚点,画图就很清楚:
direct = [(1, -2), (1, 2), (-1, 2), (-1, -2), (2, -1), (-2, -1), (2, 1), (-2, 1)]
代码如下:
# 状态搜索题型
def BFS(chessBoard, queList, row, col, finalI, finalJ):
step = 0
# 广度遍历,每个方向都走一遍
queList.append((row, col))
while queList:
t = []
# print(queList)
for xi, xj in queList:
for mi, mj in [(1, -2), (1, 2), (-1, 2), (-1, -2), (2, -1), (-2, -1), (2, 1), (-2, 1)]:
ni = xi + mi
nj = xj + mj
# print(ni, "", nj)
if 0