Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a shortest path in a graph with node and edge weights?

Let's say I have a weighted graph with weights on both edges and vertices. How do I find the "cheapest" path from a certain node s to a certain node t? My complexity should be O(n2(n+m)).

like image 519
user2023203 Avatar asked Jan 29 '13 21:01

user2023203


1 Answers

One way to solve this would be to convert the graph into a new graph in which only edges are weighted, not vertices. To do this, you can split each node apart into two nodes as follows. For any node v, make two new nodes, v1 and v2. All edges that previously entered node v now enter node v1, and all edges that leave node v now leave v2. Then, put an edge between v1 and v2 whose cost is the cost of node v.

In this new graph, the cost of a path from one node to another corresponds to the cost of the original path in the original graph, since all edge weights are still paid and all node weights are now paid using the newly-inserted edges.

Constructing this graph should be doable in time O(m + n), since you need to change each edge exactly once and each node exactly once. From there, you can just use a normal Dijkstra's algorithm to solve the problem in time O(m + n log n), giving an overall complexity of O(m + n log n). If negative weights exist, then you can use the Bellman-Ford algorithm instead, giving a total complexity of O(mn).

Hope this helps!

like image 93
templatetypedef Avatar answered Sep 28 '22 07:09

templatetypedef