【问题标题】:Linear time Graph algorithm线性时间图算法
【发布时间】:2016-04-12 01:20:48
【问题描述】:

给定一个无向图 G = (V,E),是否有一种算法可以计算两个任意顶点 u 和 v 之间最短路径的总数?我认为我们可以利用 Dijkstra 算法。

【问题讨论】:

    标签: algorithm graph shortest-path breadth-first-search depth-first-search


    【解决方案1】:

    是的,您可以使用 dijkstra。创建一个数组,存储到任何节点的最短路径总数。称之为总。所有数组成员的初始值都是 0,除了 total[s] = 1 其中 s 是源。

    在dijkstra循环中,比较一个节点的最小路径时,如果比较结果较小,则将该节点的总数组更新为当前节点的总数。如果相等,则将该节点的总数组与当前节点的总数相加。

    伪代码取自维基百科,经过一些修改:

    function Dijkstra(Graph, source):
    
      create vertex set Q
    
      for each vertex v in Graph:             // Initialization
          dist[v] ← INFINITY                  // Unknown distance from source to v
          total[v] ← 0                        // total number of shortest path
          add v to Q                          // All nodes initially in Q (unvisited nodes)
    
      dist[source] ← 0                        // Distance from source to source
      total[source] ← 1                       // total number of shortest path of source is set to 1
    
      while Q is not empty:
          u ← vertex in Q with min dist[u]    // Source node will be selected first
          remove u from Q 
    
          for each neighbor v of u:           // where v is still in Q.
              alt ← dist[u] + length(u, v)
              if alt < dist[v]:               // A shorter path to v has been found
                  dist[v] ← alt 
                  total[v] ← total[u]         // update the total array of that node with the number of total array of current node
              elseif alt = dist[v]
                  total[v] ← total[v] + total[u] // add the total array of that node with the number of total array of current node
    
      return dist[], total[]
    

    【讨论】:

    • Dijkstra 本身不会给出 any 两个任意顶点之间的最短路径计数,只是在您运行它的一个顶点与任何其他顶点之间。
    • 是的,这是因为 Dijkstra 是单源最短路径算法。但我认为问题是关于在两个任意顶点 u 和 v 之间找到最短路径的总数,没有任何顶点。如果打算“任意两个顶点”,可以使用 floyd-warshall 算法进行一些修改。而且它不是线性的。
    • 上述算法的运行时间是多少?
    • floyd Warshall算法的时间复杂度为O(V^3)
    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2012-08-09
    • 2011-05-02
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多