Python实现A*算法
时间: 2023-12-04 19:56:19 浏览: 67
下面是Python实现A*算法的示例代码:
```python
import heapq
def heuristic(a, b):
# 计算两点之间的曼哈顿距离
return abs(a[0] - b[0]) + abs(a[1] - b[1])
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[::-1]
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:
# 超出边界
continue
else:
# 超出边界
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
```
在这个示例中,我们使用了一个二维数组表示地图,1表示障碍物,0表示可以通过。起始点和目标点分别用元组表示。`heuristic`函数计算两点之间的曼哈顿距离,`astar`函数实现了A*算法的核心部分。它使用堆来搜寻下一个搜索的节点,并计算每个节点到终点的距离,然后选择最短的路径。如果找到了路径,则返回路径,否则返回False。
阅读全文