Find shortest path from Vertex u to v passing through a vertex w?

℡╲_俬逩灬. 提交于 2019-12-04 05:12:31

Find the shortest path from u to w, then the shortest path from w to v.

  1. Find shortest path from u to w
  2. Find shortest path from w to v

Then u->w->v is the shortest path.

You can do it by running Dijkstra for two times, but you can also apply the Floyd-Warshall algorithm.

Zach Langley

This problem is NP-hard, so finding a polynomial time solution is unlikely. See this cstheory post for more details.

Using the following approach we could run the algorithm just once:

set v_visisted = false
    Start from w and find shortest path to u
    if v was visited during shortest path search to u, set v_visted = true
    If v is part of shortest path from w->u then
          exit with result ( # the path would be u->v->w->v ) 
       else
           if v_visited= true then we already know values for w->v. We have a solution.
           else save path from w->v and switch u to source and find shortest path to v.

Note that running the shortest path from u to v is effectively continuing the algo's first run. Therefore, we are running the algo just once, by tracking if we visited 'v'.

Looks like finding u to w and then finding w to v, concatenating both results. Would it work?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!