Skip to content

Commit 20dbb3b

Browse files
committed
Create 787-Cheapest-Flights-Within-K-Stops.js
1 parent 52bdc09 commit 20dbb3b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} flights
4+
* @param {number} src
5+
* @param {number} dst
6+
* @param {number} k
7+
* @return {number}
8+
*/
9+
var findCheapestPrice = function(n, flights, src, dst, K) {
10+
const adjacencyList = new Map();
11+
12+
for (let [start, end, cost] of flights) {
13+
if (adjacencyList.has(start)) {
14+
adjacencyList.get(start).push([end, cost]);
15+
} else {
16+
adjacencyList.set(start, [[end, cost]]);
17+
}
18+
}
19+
20+
const queue = [[0, src, K+1]];
21+
const visited = new Map();
22+
23+
while (queue.length) {
24+
queue.sort((a, b) => a[0] - b[0]);
25+
26+
const [cost, city, stops] = queue.shift();
27+
visited.set(city, stops);
28+
29+
if (city === dst) {
30+
return cost;
31+
}
32+
33+
if (stops <= 0 || !adjacencyList.has(city)) {
34+
continue;
35+
}
36+
37+
for (let [nextCity, nextCost] of adjacencyList.get(city)) {
38+
if (visited.has(nextCity) && visited.get(nextCity) >= stops-1) {
39+
continue;
40+
}
41+
42+
queue.push([cost+nextCost, nextCity, stops-1]);
43+
}
44+
}
45+
46+
return -1;
47+
};

0 commit comments

Comments
 (0)