787 Cheapest Flights Within K Stops
Last updated
Last updated
There aren
cities connected by m
flights. Each fight starts from city u
and arrives at v
with a pricew
.
Now given all the cities and fights, together with starting citysrc
and the destination dst
, your task is to find the cheapest price fromsrc
todst
with up tok
stops. If there is no such route, output-1
.
Example 1:
Example 2:
Example 2:
Note:
The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 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.
Appoach 1: Brute Force (TLE)
The Idea: Search every possible path and check whether the current path has reached the destination, and return the minimum post path that also follows the constraints of the problem. We can make a few optimizations here like not checking paths that exceed size K in length, or not moving down paths that have accumulated a cost more than our current minimum cost.
Complexity: O(C(n,k)) time and O(k) space
Approach 2: PQ (TLE)
The Idea: Similar idea as before, but this time only take consider the current most minimum path that might reach the destination. There is still a possibility that all the paths have to be iterated through like before, but in the average case, this is a huge performance boost because the top of the heap that also contains the destination is guaranteed to be the minimum cost of all previous paths explored.
Complexity: O(log(C(n,k)) time