一种方法是编写一个函数来检查当前字段是否是目标字段,并为所有邻居递归调用此函数。在每个递归步骤中,您添加方向并在完成后返回完整路径。
dest_x = 4
dest_y = 1
visited = []
def next (path, x, y):
visited.append ([x, y])
# obstacle
if matrix[x][y] == 0:
return None
# found destination
if x == dest_x and y == dest_y:
return path
for i in [{'x': x - 1, 'y': y, 'direction': 'left'},
{'x': x + 1, 'y': y, 'direction': 'right'},
{'x': x, 'y': y - 1, 'direction': 'up'},
{'x': x, 'y': y + 1, 'direction': 'down'}]:
if [i['x'], i['y']] not in visited and i['x'] >= 0 and i['x'] < len(matrix) and i['y'] >= 0 and i['y'] < len(matrix[x]):
n = next (path + [i['direction']], i['x'], i['y'])
if n != None:
return n
matrix = [[1,1,1,1],
[1,1,1,1],
[1,0,0,1],
[1,1,1,1],
[1,1,1,1]]
print (next ([], 0, 1))
如果有的话,这会找到一种方法。如果您需要最短的方式,您可以在到达目的地时将路径存储在数组中,而不是返回它。找到所有路径后,您可以打印最小长度的路径