Created
June 15, 2020 10:42
-
-
Save dmngu9/ee59da89f1f7ba0f28596d4772024ee2 to your computer and use it in GitHub Desktop.
Cheap flights within k stops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var findCheapestPrice = function(n, flights, src, dst, K) { | |
let ins = new Array(n).fill(0).map(r => []) | |
for (const [from, to, cost] of flights) { | |
ins[to].push([from, cost]) | |
} | |
let dp = new Array(K+2).fill(0).map(r => new Array(n).fill(Number.MAX_SAFE_INTEGER)) | |
for (let i = 0; i <= (K+1); i++) { | |
for (let j = 0; j < n; j++) { | |
if (j === src) { | |
dp[i][j] = 0 | |
} else { | |
if (i === 0) { | |
continue | |
} | |
for (const [stop, cost] of ins[j]) { | |
dp[i][j] = Math.min(dp[i][j], cost + dp[i-1][stop]) | |
} | |
} | |
} | |
} | |
return dp[K+1][dst] === Number.MAX_SAFE_INTEGER ? -1 : dp[K+1][dst] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment