mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 07:29:47 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
46 lines
1.0 KiB
JavaScript
46 lines
1.0 KiB
JavaScript
// Problem Statement => https://www.youtube.com/watch?v=lBRtnuxg-gU
|
|
|
|
const minCostPath = (matrix) => {
|
|
/*
|
|
Find the min cost path from top-left to bottom-right in matrix
|
|
>>> minCostPath([[2, 1], [3, 1], [4, 2]])
|
|
>>> 6
|
|
*/
|
|
|
|
const n = matrix.length
|
|
const m = matrix[0].length
|
|
|
|
// moves[i][j] => minimum number of moves to reach cell i, j
|
|
const moves = new Array(n)
|
|
for (let i = 0; i < moves.length; i++) moves[i] = new Array(m)
|
|
|
|
// base conditions
|
|
moves[0][0] = matrix[0][0] // to reach cell (0, 0) from (0, 0) is of no moves
|
|
for (let i = 1; i < m; i++) moves[0][i] = moves[0][i - 1] + matrix[0][i]
|
|
for (let i = 1; i < n; i++) moves[i][0] = moves[i - 1][0] + matrix[i][0]
|
|
|
|
for (let i = 1; i < n; i++) {
|
|
for (let j = 1; j < m; j++) {
|
|
moves[i][j] = Math.min(moves[i - 1][j], moves[i][j - 1]) + matrix[i][j]
|
|
}
|
|
}
|
|
|
|
return moves[n - 1][m - 1]
|
|
}
|
|
|
|
export { minCostPath }
|
|
|
|
// Example
|
|
|
|
// minCostPath([
|
|
// [2, 1],
|
|
// [3, 1],
|
|
// [4, 2]
|
|
// ])
|
|
|
|
// minCostPath([
|
|
// [2, 1, 4],
|
|
// [2, 1, 3],
|
|
// [3, 2, 1]
|
|
// ])
|