-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0787-cheapest-flights-within-k-stops.ts
More file actions
45 lines (36 loc) · 1.03 KB
/
0787-cheapest-flights-within-k-stops.ts
File metadata and controls
45 lines (36 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function findCheapestPrice(
n: number,
flights: number[][],
src: number,
dst: number,
k: number,
): number {
const adjacencyList = new Map();
for (let [start, end, cost] of flights) {
if (adjacencyList.has(start)) {
adjacencyList.get(start).push([end, cost]);
} else {
adjacencyList.set(start, [[end, cost]]);
}
}
const queue = [[0, src, k + 1]];
const visited = new Map();
while (queue.length) {
queue.sort((a, b) => a[0] - b[0]);
const [cost, city, stops] = queue.shift();
visited.set(city, stops);
if (city === dst) {
return cost;
}
if (stops <= 0 || !adjacencyList.has(city)) {
continue;
}
for (let [nextCity, nextCost] of adjacencyList.get(city)) {
if (visited.has(nextCity) && visited.get(nextCity) >= stops - 1) {
continue;
}
queue.push([cost + nextCost, nextCity, stops - 1]);
}
}
return -1;
}