How do I find the shortest path that covers all nodes in a directed cyclic graph?

后端 未结 4 2117
一整个雨季
一整个雨季 2020-12-18 05:05

I need an example of the shortest path of a directed cyclic graph from one node (it should reach to all nodes of the graph from a node that will be the input).

Pleas

4条回答
  •  生来不讨喜
    2020-12-18 05:56

    In Pseudocode:

    //INPUT: graph G = (V,E)
    //OUTPUT: shortest cycle length
    min_cycle(G)
      min = ∞
      for u in V
        len = dij_cyc(G,u)
        if min > len
          min = len
      return min    
    
    //INPUT: graph G and vertex s
    //OUTPUT: minimum distance back to s
    dij_cyc(G,s)
      for u in V
        dist(u) = ∞
                       //makequeue returns a priority queue of all V
      H = makequeue(V) //using dist-values as keys with s First In
      while !H.empty?
        u = deletemin(H)
        for all edges (u,v) in E
          if dist(v) > dist(u) + l(u,v) then
            dist(v) = dist(u) + l(u,v)
            decreasekey(H,v)
    
      return dist(s)
    

    This runs a slightly different Dijkstra's on each vertex. The mutated Dijkstras has a few key differences. First, all initial distances are set to ∞, even the start vertex. Second, the start vertex must be put on the queue first to make sure it comes off first since they all have the same priority. Finally, the mutated Dijkstras returns the distance back to the start node. If there was no path back to the start vertex the distance remains ∞. The minimum of all these returns from the mutated Dijkstras is the shortest path. Since Dijkstras runs at worst in O(|V|^2) and min_cycle runs this form of Dijkstras |V| times, the final running time to find the shortest cycle is O(|V|^3). If min_cyc returns ∞ then the graph is acyclic.

    To return the actual path of the shortest cycle only slight modifications need to be made.

提交回复
热议问题