简体   繁体   中英

Weighted Directed Graph best method for shortest path

For a question I was doing I'm confused about why the answer would be a BFS and not Dijkstra's algorithm.

The question was: There is a weighted digraph G=(V,E) with n nodes and m edges. Each node has a weight of 1 or 2. The question was to figure out which algorithm to use to find the shortest path in G from a given vetex u to a given vertex v. The options were:

a) O(n+m) time using a modified BFS
b) O(n+m) time using a modified DFS
c) O(mlogn) time using Dijkstra's Algorithm
d) O(n^3) time using modified Floyd-Warshall algorithm

The answer is a) O(n+m) time using a modified BFS,

I know that when comparing BFS to DFS, BFS is better for shorter paths. I also know Dijkstra's algorithm is similar to a BFS and if I'm not mistaken Dijkstra's algorithm is better for weighted graphs like in this case. I'm assuming BFS is better because it says modified BFS but what would modified exactly mean or is there another reason BFS would be better.

Since all paths are limited to either a distance of 1 or 2, for every edge of length 2 from nodes a to b you can just create a new node c with an edge from a to c of length 1 and an edge from c to b of length 1, and then this becomes a graph with only edges of weight 1 which can be BFS 'd normally to find shortest path from u to v . Since you only add O(m) new nodes and O(m) new edges, this keeps the BFS's time complexity of O(n+m) .

Another possibility is to, at each layer of BFS, store another list of nodes that are attained by edges with a weight of 2 from the current layer, and consider them at the same time as nodes attained two layers later. This approach is a bit more finicky though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM