我的任务如下。我有一个开始顶点,一个结束顶点。我需要找到两者之间的最短路径。 在我的代码中,我能够找到最短路径成本,但我不明白如何返回与该成本相对应的路径。
输入是如下形式的图 [[vertex_from,vertex_to,cost],[vertex_from,vertex_to,cost]...]
def belmanford(adj_matrix, v_from, v_to):
n, graph = len(graphe(adj_matrix)), adj_matrix
dist = [float("inf") for i in range(n)] # all vertices are considered not visited
dist[v_from]=0#cost from start vertex to end vertex is null
for i in range(1,n):
for u,v,c in graph:#iterating over all vertices
if dist[u] != float("inf") and dist[u] +c < dist[v]:
dist[v] = dist[u] + c #we have in dist all distances from vertex start to another one and we replace them when we find a better one
if dist[v_to]!=float("inf"):
return dist[v_to]#shortest path
else:
return -1
测试用例示例:
adj_matrix =[[0, 1, 5], [0, 2, 2], [1, 0, 5], [2, 0, 2]]
result=[0,2]