我要違揹我的直覺,並認爲這不是作業。你必須利用拓撲排序給你的信息。每當你以拓撲順序檢查節點n時,你都可以保證你已經遍歷了每條可能的路徑。使用這種很明顯地看到,您可以用拓撲排序(僞)的一個線性掃描生成的最短路徑:
Graph g
Source s
top_sorted_list = top_sort(g)
cost = {} // A mapping between a node, the cost of its shortest path, and
//its parent in the shortest path
for each vertex v in top_sorted_list:
cost[vertex].cost = inf
cost[vertex].parent = None
cost[s] = 0
for each vertex v in top_sorted_list:
for each edge e in adjacensies of v:
if cost[e.dest].cost > cost[v].cost + e.weight:
cost[e.dest].cost = cost[v].cost + e.weight
e.dest.parent = v
現在你可以從s查找任何最短路徑到目的地。您只需要在成本映射中查找目的地,獲取它的父級,然後重複此過程,直到獲得父級爲s的節點,然後您擁有最短路徑。
爲了澄清,你想找到最低的距離,還是最少的邊數?邊緣有不同的長度嗎? – 2009-09-27 02:16:27
另外,你可以在最短的路徑上回溯鏈接,還是隻能往下走? – 2009-09-27 02:17:26