I chose to solve this by performing Djikstra's in reverse (from destination to source).
Going in reverse seems to be necessary so as to not exhaust a possible sub k-length route
when greedily taking the cheapest path.
A simple BFS is strictly better than Djikstra's for this problem, being as there is a hard cap on the length of the path.
_55 int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst,
_55 // build adjacency list (reverse edge direction)
_55 vector<vector<pair<int, int>>> adj(n);
_55 for (auto &flight : flights) {
_55 adj[flight[1]].emplace_back(flight[0], flight[2]);
_55 auto cheapest = [](const flight &a, const flight &b) {
_55 return a.cost > b.cost;
_55 int mincost = INT_MAX;
_55 vector<vector<bool>> flew(n, vector<bool>(n, false));
_55 // djikstra's with limit
_55 vector<bool> seen(n, false);
_55 priority_queue<flight, vector<flight>, decltype(cheapest)> pq(cheapest);
_55 pq.push({0, dst, 0});
_55 while (!pq.empty()) {
_55 auto [cost, airport, len] = pq.top();
_55 for (auto [nei, price] : adj[airport]) {
_55 if (nei == src && len <= k) {
_55 mincost = min(mincost, cost + price);
_55 if (!flew[airport][nei] && len + 1 <= k) {
_55 flew[airport][nei] = true;
_55 pq.push({cost + price, nei, len + 1});
_55 return mincost == INT_MAX ? -1 : mincost;
If you found this solution helpful, consider leaving a star!