修改Dijkstra算法以获得两个节点之间的最短路径

时间:2012-11-19 03:15:57

标签: data-structures graph graph-theory dijkstra

所以我看到了类似的问题,但并不完全是我正在寻找的。我需要修改Dijkstra的算法以返回顶点S(源)和顶点X(目标)之间的最短路径。我想我已经想出了该怎么做,但我想要一些帮助。这是我修改过的伪代码。

 1  function Dijkstra(Graph, source, destination):
 2      for each vertex v in Graph:                                // Initializations
 3          dist[v] := infinity ;                                  // Unknown distance function from 
 4                                                                 // source to v
 5          previous[v] := undefined ;                             // Previous node in optimal path
 6      end for                                                    // from source
 7      
 8      dist[source] := 0 ;                                        // Distance from source to source
 9      Q := the set of all nodes in Graph ;                       // All nodes in the graph are
10                                                                 // unoptimized - thus are in Q
11      while Q is not empty:                                      // The main loop
12          u := vertex in Q with smallest distance in dist[] ;    // Start node in first case
13          remove u from Q ;
14          if dist[u] = infinity:
15              break ;                                            // all remaining vertices are
16          end if                                                 // inaccessible from source
17          
18          for each neighbor v of u:                              // where v has not yet been 
19                                                                 // removed from Q.
20              alt := dist[u] + dist_between(u, v) ;
21              if alt < dist[v]:                                  // Relax (u,v,a)
22                  dist[v] := alt ;
23                  previous[v] := u ;
24                  decrease-key v in Q;                           // Reorder v in the Queue
25              end if
26          end for
27      end while
28  return dist[destination];

代码取自维基百科并修改:http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm

这看起来是否正确?

3 个答案:

答案 0 :(得分:4)

Dijkstra的算法不需要修改,它是一对全对最短路径算法。看起来你正试图找到两个特定节点之间的最短路径--Dijkstra处理这个问题。

如果你想要一些专门为未加权的无向图设计的东西,这就像你正在做的那样,我建议做一个BFS。

答案 1 :(得分:4)

在找到从单个SOURCE开始的最短路径之后,我们需要从DESTINATION开始回溯它的前任,以便打印路径。

Print-Path(G,s,v)
{
    if(v==s)
        print s;
    else if (pi[v]==NULL)       
        print "no path from "+s+" to "+v;
    else{
        Print-Path(G,s,pi[v])
        print v;
    }
}

代码为“算法简介”,麻省理工学院出版社

答案 2 :(得分:2)

解决此问题的最佳方法是根据从每个可到达节点返回源的路径进行思考,通常用v表示。当您更新每个给定节点的距离时,请跟踪其直接后继路径v。该节点是最短距离到v树中给定节点的父节点。当您构建该父映射时,要找到从v到w的最短路径,请按相反的顺序构建路径:w,parent [w],parent [parent [w]],...