将Dijkstra转换为Python中的星级算法
我正在尝试将Dijkstra Min Heap(优先队列)算法转换为具有启发式方法的A* - 我适应的Dijkstra算法在这里: =“ https://bradfieldcs.com/algos/graphs/dijkstras-algorithm/”
如果 f = g + h
, ,然后
我已经修改了存储元组的优先级队列:(f,g,vertex)
per @btilly在下面注释 - 因此,它将在每个上拉出最低
我还添加了访问的集合。 f_distance
heappop()
import heapq
# V+ElogE time / E space
def a_star(graph, start, dest, heuristic):
distances = {vertex: float('inf') for vertex in graph} # V time / V space
distances[start] = 0
parent = {vertex: None for vertex in graph} # store path => V time / V space
visited = set()
pq = [( 0 + heuristic[start], 0 , start)] # E space
while pq: # ElogE time
curr_f, curr_dist, curr_vert = heapq.heappop(pq) #logE time
if curr_vert not in visited:
visited.add(curr_vert)
for nbor, weight in graph[curr_vert].items():
distance = curr_dist + weight # distance from start (g)
f_distance = distance + heuristic[nbor] # f = g + h
# Only consider this new path if it's f_distance is better
if f_distance < distances[nbor]:
distances[nbor] = f_distance
parent[nbor] = curr_vert
if nbor == dest:
# we found a path based on heuristic
return distances, parent
heapq.heappush(pq, (f_distance, distance, nbor)) #logE time
return distances, parent
graph = {
'A': {'B':3, 'H':4, 'F': 1},
'B': {'A': 3, 'C':5 },
'C': {'B':5, 'D':6, 'I':2},
'D': {'C':6, 'E':1},
'E': {'D':1, 'I':2, 'G':20},
'F': {'A':1, 'G':1},
'G': {'F':1, 'E':20},
'H': {'A':4, 'I':8, },
'I': {'H':8, 'C':2, 'E':2},
}
heuristic = {
'A': 20,
'B': 19,
'C': 16,
'D': 12,
'E': 0,
'F': 13,
'G': 11,
'H': 15,
'I': 10,
}
start = 'A'
dest= 'E'
distances,parent = a_star(graph, start, dest, heuristic)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议阅读 。这是一个非常有用的API,实施了所谓的Dijkstraheap ,并基于以下方式计算成本启发式:
I'd suggest reading this implementation of the A* Algorithm by Python core dev Pablo Salgado. It's a very Pythonic API implementing a so-called DijkstraHeap and calculating the cost heuristics intuitively based on:
这是生成路径的完整代码。该图基于此
路径=&gt; a-&gt; b-&gt; d-&gt; k-&gt; p
Here's the full code to generate the path . The graph is based on this youtube:
path => A->B->D->K->P