Cheapest Flights Within K Stops

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.

flights.cpp

_55
#include <iostream>
_55
#include <queue>
_55
#include <vector>
_55
_55
using namespace std;
_55
_55
class Solution {
_55
public:
_55
struct flight {
_55
int cost, dest, len;
_55
};
_55
int findCheapestPrice(int n, vector<vector<int>> &flights, int src, int dst,
_55
int k) {
_55
_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
}
_55
_55
// minq comparator
_55
auto cheapest = [](const flight &a, const flight &b) {
_55
return a.cost > b.cost;
_55
};
_55
_55
int mincost = INT_MAX;
_55
_55
vector<vector<bool>> flew(n, vector<bool>(n, false));
_55
_55
// djikstra's with limit
_55
vector<bool> seen(n, false);
_55
seen[dst] = true;
_55
priority_queue<flight, vector<flight>, decltype(cheapest)> pq(cheapest);
_55
pq.push({0, dst, 0});
_55
_55
while (!pq.empty()) {
_55
auto [cost, airport, len] = pq.top();
_55
pq.pop();
_55
_55
for (auto [nei, price] : adj[airport]) {
_55
_55
if (nei == src && len <= k) {
_55
mincost = min(mincost, cost + price);
_55
}
_55
_55
if (!flew[airport][nei] && len + 1 <= k) {
_55
flew[airport][nei] = true;
_55
pq.push({cost + price, nei, len + 1});
_55
}
_55
}
_55
}
_55
_55
return mincost == INT_MAX ? -1 : mincost;
_55
}
_55
};

If you found this solution helpful, consider leaving a star!