我目前正在玩着名的Dijkstra算法,并且有点卡住了。我试图修改伪代码以获取源和目标的输入,努力在实现的图形中找到两个顶点之间的SHORTEST路径。我希望输入SOURCE和DEST为字符串值。我也在尝试修改,所以输入只是列表SHORTEST PATH。关于如何修改算法来获取此问题的任何想法?
1: function Dijkstra(Graph, source):
2: for each vertex v in Graph: // Initialization
3: dist[v] := infinity // initial distance from source to vertex v is set to infinite
4: previous[v] := undefined // Previous node in optimal path from source
5: dist[source] := 0 // Distance from source to source
6: Q := the set of all nodes in Graph // all nodes in the graph are unoptimized - thus are in Q
7: while Q is not empty: // main loop
8: u := node in Q with smallest dist[ ]
9: remove u from Q
10: for each neighbor v of u: // where v has not yet been removed from Q.
11: alt := dist[u] + dist_between(u, v)
12: if alt < dist[v] // Relax (u,v)
13: dist[v] := alt
14: previous[v] := u
15: return previous[ ]
答案 0 :(得分:0)
简单,将DESTINATION添加为您的函数接受作为输入的参数,并像往常一样继续算法。只需删除最后一行
return previous[ ]
添加以下行,仅为最短路径中的节点访问前一个[]列表。您从DEST节点开始此遍历,直到您到达SOURCE
x := DEST
shortest_path := []
while x is not equal to SOURCE:
shortest_path.add(x)
x := previous[x]
shortest_path.add(x) //finally add the SOURCE outside the loop
return shortest_path[]
要将SOURCE和DEST作为字符串值,您需要一个带有字符串的例程,并返回该Graph中的Node,其中包含输入字符串给出的值。
Algorithm getNodeFromString(Graph G, String s):
for every node N in G:
if N.id == s:
return N
当然,这是假设Graph中的每个节点都有唯一的标识符。