Skip to content

Commit 89ccb83

Browse files
authored
Update 787-cheapest-flights-within-k-stops.js
1 parent a08249c commit 89ccb83

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

787-cheapest-flights-within-k-stops.js

+43
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
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+
const findCheapestPrice = function(n, flights, src, dst, K) {
10+
const arr = Array(n).fill(Infinity)
11+
arr[src] = 0
12+
const g = {}
13+
for(const [u,v,p] of flights) {
14+
if(g[u] == null) g[u] = []
15+
g[u].push([v, p])
16+
}
17+
18+
let step = 0
19+
let q = [[src,0]]
20+
while(step < K + 1 && q.length) {
21+
const len = q.length
22+
const row = []
23+
for(let i = 0; i < len; i++) {
24+
const el = q[i]
25+
const [s, dis] = el
26+
for(const e of (g[s] || [])) {
27+
const [nxt, p] = e
28+
if(arr[nxt] > p + dis) {
29+
arr[nxt] = p + dis
30+
row.push([nxt, arr[nxt]])
31+
}
32+
33+
}
34+
}
35+
q = row
36+
step++
37+
}
38+
39+
return arr[dst] === Infinity ? -1 : arr[dst]
40+
}
41+
42+
// another
43+
144
/**
245
* @param {number} n
346
* @param {number[][]} flights

0 commit comments

Comments
 (0)