function findCheapestPrice(n, flights, src, dst, k) {
const adj = new Map();
for (const [from, to, price] of flights) {
if (!adj.has(from)) adj.set(from, []);
adj.get(from).push([to, price]);
}
const queue = [[src, 0, 0]]; // [city, cost, stops]
const minCost = Array.from({ length: n }, () => Array(k + 2).fill(Infinity));
minCost[src][0] = 0;
while (queue.length) {
const [city, cost, stops] = queue.shift();
if (stops > k) continue;
const neighbors = adj.get(city) || [];
for (const [next, price] of neighbors) {
const newCost = cost + price;
if (newCost < minCost[next][stops + 1]) {
minCost[next][stops + 1] = newCost;
queue.push([next, newCost, stops + 1]);
}
}
}
const result = Math.min(...minCost[dst]);
return result === Infinity ? -1 : result;
}
console.log(findCheapestPrice(4, [[0,1,100],[1,2,100],[2,3,100],[0,3,500]], 0, 3, 1)); // 500
console.log(findCheapestPrice(4, [[0,1,100],[1,2,100],[2,3,100],[0,3,500]], 0, 3, 2)); // 300