Cheapest Flights Within K Stops
LeetCode Problem #787
Problem Statement
There are n
cities connected by m
flights. Each flight starts from city u
and arrives at v
with a price w
.
Now given all the cities and flights, together with starting city src
and the destination dst
, your task is to find the cheapest price from src
to dst
with up to k
stops. If there is no such route, output -1
.
Testcases
Problem Explanation
There are several possible paths that can be taken to reach a particular destination city from a source city. In this problem, there are intermediate cities through which one can travel in order to reach their destination. However, the problem stipulates that we cannot travel through more than a given number of intermediate cities.
The problem asks us to find the lowest price that we have to pay to reach the destination from the source, given that we can stop at a maximum of k
stops. Including the destination city, this means that k + 1
nodes may be traversed in the flight path.
Prerequisite Knowledge
Priority Queue
A priority queue is a special type of queue wherein, every element is associated with a priority value and is processed according to the magnitude of this value.
While the conventional queue data structure follows a first-in-first-out (FIFO) but in the case of a priority queue, the values are dequeued on the basis of their priority value.
In the example below, a higher number indicates a higher priority, but the priority parameters can be designed according to our needs.
Graph Data Structure
A graph is a non-linear data structure which comprises a finite number of nodes (vertices) and a set of edges which connect a pair of nodes.
Every edge in a graph is represented as an ordered pair of vertices.
In the example below, the nodes or vertices are represented as, 0, 1, 2, 3
The edges connecting these nodes are represented as, {0, 1}, {0, 2}, {0, 3}, {1, 2}
Two nodes are said to have adjacency if they have an edge which connects them. In order to traverse from a source node to a destination node through other nodes, we follow a sequence of edges called a path.
Adjacency Matrix
A common way to represent a graph is through an adjacency matrix.
The relationship between each node and the other nodes in the graph is represented using a two-dimensional matrix with the number of rows and columns equal to the number of nodes in the graph.
If an edge exists between two nodes, i
and j
, cell a[i, j]
will be filled with the value 1. If there is no edge connection between the two nodes, the respective cell is filled with the value 0.
Image Sources:
Dijkstra's Algorithm
Dijkstra's Algorithm is used to find the shortest path between any two nodes of a graph. The algorithm accomplishes this by building a set of nodes that have a minimum distance from the source.
This algorithm can be applied to weighted graphs. A weighted graph is simply a graph where the edges which connect some nodes have a non-negative value or cost associated with it. In this problem, the price of the flight is considered as the weight.
Algorithm
Dijkstra's Algorithm Approach
This approach is based on Dijkstra's Algorithm, with the primary difference being that a global optimum value is not maintained. The global optimum is not needed in this case because the distance is not the only parameter which must be concerned, and by extension, evaluated for optimization. There could be routes wherein, the distance is shorter, but go through more stops. If this is not allowed according to the constraints, it cannot be considered as the optimal route.
A priority queue is used to store all possible routes with 0 to K
stops such that they can all be processed.
Initialize a mapping which stores the flight information as:
<source city, <destination city, <price>>
Initialize a min priority queue with each object being an integer array holding values:
a. Current total price
b. Current source city
c. Maximum allowed hops to destination
The priority queue compares each object with the total price so far.
Add the original source city to the priority queue and set the price to 0 and the number of hops allowed to
k + 1
.While there are cities remaining to be traversed,
a. Identify and remove the minimum object from the priority queue.
b. Get the current total price, the current source city, and the number of hops to the destination allowed from the minimum object.
Check if the current source is equal to the destination and the number of stops made is less than
k
.a. If the destination has been reached and the conditions are satisfied, return the distance value.
b. If the destination has not been reached, find all the connected flights that fly from the current source. Calculate the new price, identify the current source, find the new distance, and add these values to the priority queue.
If there are no cities remaining to be traversed or no flights that satisfy the conditions, return -1.
Code
Last updated
Was this helpful?