gpt4 book ai didi

python - 将 dijkstras 转换为 * python

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:43 27 4
gpt4 key购买 nike

所以,假设我在 dijkstras.py 中有一些代码可以在给定图 G 的情况下执行 dijkstras。

def shortest_path(G, start, end):
def flatten(L): # Flatten linked list of form [0,[1,[2,[]]]]
while len(L) > 0:
yield L[0]
L = L[1]
q = [(0, start, ())] # Heap of (cost, path_head, path_rest).
visited = set() # Visited vertices.
while True:
(cost, v1, path) = heapq.heappop(q)
if v1 not in visited:
visited.add(v1)
if v1 == end:
return [('cost', cost)] + [('path', list(flatten(path))[::-1] + [v1])]
path = (v1, path)
for (v2, cost2) in G[v1].iteritems():
if v2 not in visited:
heapq.heappush(q, (cost + cost2, v2, path))

G 是这样的:

 G = {
's': {'u':10, 'x':5},
'u':{'v':1, 'x':2},
'v':{'y':4},
'x':{'u':3, 'v':9, 'y':2},
'y': {'s':7, 'v':6}
}

我们如何转换现有算法,shortest_path(G, start, end) 以利用 a* 进行最少的修改。

我的想法是:

def shortest_path(G, start, end, h): #where h is the heuristic function
def flatten(L): # Flatten linked list of form [0,[1,[2,[]]]]
while len(L) > 0:
yield L[0]
L = L[1]
q = [(0, start, ())] # Heap of (cost, path_head, path_rest).
visited = set() # Visited vertices.
while True:
(cost, v1, path) = heapq.heappop(q)
if v1 not in visited:
visited.add(v1)
if v1 == end:
return [('cost', cost)] + [('path', list(flatten(path))[::-1] + [v1])]
path = (v1, path)
for (v2, cost2) in G[v1].iteritems():
if v2 not in visited:
heapq.heappush(q, (cost + cost2 + h(v2), v2, path)) #modification here

但我什至还没有运行它,所以我不知道它会如何运行。在我开始编写更多代码之前,我只是想从某人身上反弹这个。

最佳答案

正如 alfa 所建议的,正确的解决方案是使用 cost + cost2 + h(v2)

关于python - 将 dijkstras 转换为 * python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990359/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com