[LeetCode] Cheapest Flights Within K Stops

787. Cheapest Flights Within K Stops

There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.

You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
int grid[100]{[0 ... 99] = (int)1e7}, cGrid[100]{[0 ... 99] = (int)1e7};
grid[src] = cGrid[src] = 0;
do {
for(auto& f : flights) {
cGrid[f[1]] = min(cGrid[f[1]], grid[f[0]] + f[2]);
}
memcpy(grid, cGrid, n * sizeof(int));
}while(k--);
return grid[dst] == 1e7 ? -1 : grid[dst];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/12/PS/LeetCode/cheapest-flights-within-k-stops/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.