【问题标题】:How to find shortest path in a equal weighted graph如何在等权图中找到最短路径
【发布时间】:2016-08-07 07:11:48
【问题描述】:

我有一个看起来像这样的图表: 节点之间的所有边的距离 = 1。

      F
      |
      E
      |
A-B-C-D
|     |
G     O
|     |
H     P
|     |
I     Q
|     |
J     R
|     |
K-L-M-N

我必须找到从 A 节点到 Q 的最短路径。 我使用的算法如下(借自维基百科):

 1 function Dijkstra(Graph, source):
 2
 3      create vertex set Q
 4
 5      for each vertex v in Graph:             // Initialization
 6          dist[v] ← INFINITY                  // Unknown distance from source to v
 7          prev[v] ← UNDEFINED                 // Previous node in optimal path from source
 8          add v to Q                          // All nodes initially in Q (unvisited nodes)
 9
10      dist[source] ← 0                        // Distance from source to source
11      
12      while Q is not empty:
13          u ← vertex in Q with min dist[u]    // Source node will be selected first
14          remove u from Q 
15          
16          for each neighbor v of u:           // where v is still in Q.
17              alt ← dist[u] + length(u, v)
18              if alt < dist[v]:               // A shorter path to v has been found
19                  dist[v] ← alt 
20                  prev[v] ← u 
21
22      return dist[], prev[]

当我使用 djikstra 的算法时,主要问题是我无法获得从源到目的地的最短路径。 算法遍历不在最短路径中的节点,找到最短路径。

E.g if i traverse from A->Q i traverse through other nodes like(G->H->I..)
But the path from G->H->I does not lead to the destination.
But the path from A->B->C... leads to the shortest path.

如何回溯正确的路径?

【问题讨论】:

    标签: shortest-path


    【解决方案1】:

    这就是 djikstra 算法中 prev 数组的用途

    你知道目的地是 Q,所以 prev[Q] 是最优路径中 Q 之前的节点(在这种情况下是 P)

    prev[P] 是 O,prev[O] 是 D,依此类推,直到到达路径的起点 A。

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2014-04-14
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多