There arencities connected by mflights. Each fight starts from city uand arrives at vwith a pricew.
Now given all the cities and flights, together with starting citysrcand the destination dst, your task is to find the cheapest price fromsrctodstwith up tokstops. If there is no such route, output-1.
Example 1:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output:
200
Explanation:
The graph looks like this:
0
/ \
100 500
/ \
1 ---100--- 2
The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output:
500
Explanation:
The graph looks like this:
0
/ \
100 500
/ \
1 ---100--- 2
The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked red in the picture.
Note:
The number of nodes nwill be in range[1, 100], with nodes labeled from0ton - 1.
The size of flights will be in range [0, n * (n - 1) / 2].
The format of each flight will be (src, dst, price).
The price of each flight will be in the range [1, 10000].
k is in the range of [0, n - 1].
There will not be any duplicated flights or self cycles.
Solution
Dijkstra's Algorithm (BFS) with PriorityQueue Implementation
The key difference with the classic Dijkstra algo is, we don't maintain the global optimal distance to each node, i.e. ignore below optimization:
alt ← dist[u] + length(u, v)
if alt < dist[v]:
Because there could be routes which their length is shorter but pass more stops, and those routes don't necessarily constitute the best route in the end. To deal with this, rather than maintain the optimal routes with 0..K stops for each node, the solution simply put all possible routes into the priority queue, so that all of them has a chance to be processed. IMO, this is the most brilliant part.
And the solution simply returns the first qualified route, it's easy to prove this must be the best route.
Complexity Analysis
Time Complexity: O(E+nlogn), where E is the total number of flights.?