The problem:
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 cityfromi
to citytoi
with costpricei
.You are also given three integers
src
,dst
, andk
, return the cheapest price fromsrc
todst
with at mostk
stops. If there is no such route, return-1
.
My solution, implemented in JavaScript:
var findCheapestPrice = function(n, flights, src, dst, k) {
// generate a graph
let map = new Map();
for(let i=0; i<flights.length; i++) {
const [orig, des, cost] = flights[i];
const temp = map.get(orig) || []
temp.push([des, cost]);
map.set(orig, temp);
}
// start from the source with cost 0
// [cost, city, available stops]
let queue = [[0,src,k+1]]
while(queue.length > 0) {
const [cost, city, stops] = queue.shift();
if(city === dst) return cost; // Get in the destination
// still have available stops
if(stops > 0) {
const possibleFlights = map.get(city) || [];
for(const pf of possibleFlights) {
// current cost + flight cost
// decrement stops (one stop to this airport)
queue.push([cost+pf[1], pf[0], stops-1]);
}
// Sort by the cheapest next flight (Heap?)
queue.sort((a,b) => a[0]-b[0]);
}
}
// couldn't find a path
return -1;
};
It works just fine with the basic case tests, but it fails with time limit exceed for the test case below. Is there a way to improve the code?
13
[[11,12,74],[1,8,91],[4,6,13],[7,6,39],[5,12,8],[0,12,54],[8,4,32],[0,11,4],[4,0,91],[11,7,64],[6,3,88],[8,5,80],[11,10,91],[10,0,60],[8,7,92],[12,6,78],[6,2,8],[4,3,54],[3,11,76],[3,12,23],[11,6,79],[6,12,36],[2,11,100],[2,5,49],[7,0,17],[5,8,95],[3,9,98],[8,10,61],[2,12,38],[5,7,58],[9,4,37],[8,6,79],[9,0,1],[2,3,12],[7,10,7],[12,10,52],[7,2,68],[12,2,100],[6,9,53],[7,4,90],[0,5,43],[11,2,52],[11,8,50],[12,4,38],[7,9,94],[2,7,38],[3,7,88],[9,12,20],[12,0,26],[10,5,38],[12,8,50],[0,2,77],[11,0,13],[9,10,76],[2,6,67],[5,6,34],[9,7,62],[5,3,67]]
10
1
10
src
todst
, it will be returned at the very first iteration. Indirect flights (which could be cheaper) are not considered. \$\endgroup\$