使用def find route(arr,m,n)作为开头函数使用
arr作为迷宫矩阵
m表示矩阵行数
n表示矩阵列数
用点坐标列表表示
下面是一个Python实现的A*算法用于迷宫寻路的示例代码,你可以参考下面的代码实现:
import heapq
def heuristic(a, b):
return (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2
def astar(array, start, goal):
neighbors = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
close_set = set()
came_from = {}
gscore = {start:0}
fscore = {start:heuristic(start, goal)}
oheap = []
heapq.heappush(oheap, (fscore[start], start))
while oheap:
current = heapq.heappop(oheap)[1]
if current == goal:
data = []
while current in came_from:
data.append(current)
current = came_from[current]
return data
close_set.add(current)
for i, j in neighbors:
neighbor = current[0] + i, current[1] + j
tentative_g_score = gscore[current] + heuristic(current, neighbor)
if 0 <= neighbor[0] < array.shape[0]:
if 0 <= neighbor[1] < array.shape[1]:
if array[neighbor[0]][neighbor[1]] == 1:
continue
else:
# array bound y walls
continue
else:
# array bound x walls
continue
if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
continue
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1]for i in oheap]:
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(oheap, (fscore[neighbor], neighbor))
return False
其中,arr是一个二维矩阵,1表示障碍物,0表示可以通过的地方;start和goal是起点和终点的坐标。函数返回一个路径,如果无法找到路径则返回False。你可以将arr、m、n转换为点坐标列表的形式来调用此函数,示例代码如下:
import numpy as np
arr = np.array([
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
])
m, n = arr.shape
start = (0, 0)
goal = (4, 3)
path = astar(arr, start, goal)
if path:
print("Path found: ", path[::-1])
else:
print("Path not found")
你需要根据你自己的数据结构来适当地修改代码。