Update MinimumCostPath.js

This commit is contained in:
DhruvGheewala
2020-12-20 20:08:30 +05:30
parent 8dd159f37b
commit 902b1dfe35

View File

@ -1,37 +1,46 @@
// youtube Link -> https://www.youtube.com/watch?v=lBRtnuxg-gU // Problem Statement => https://www.youtube.com/watch?v=lBRtnuxg-gU
const minCostPath = (matrix) => { const minCostPath = (matrix) => {
/* /*
Find the min cost path from top-left to bottom-right in matrix Find the min cost path from top-left to bottom-right in matrix
>>> minCostPath([[2, 1], [3, 1], [4, 2]]) >>> minCostPath([[2, 1], [3, 1], [4, 2]])
6 >>> 6
*/ */
const n = matrix.length const n = matrix.length
const m = matrix[0].length const m = matrix[0].length
// Preprocessing first row // moves[i][j] => minimum number of moves to reach cell i, j
for (let i = 1; i < m; i++) { const moves = new Array(n)
matrix[0][i] += matrix[0][i - 1] 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]
// Preprocessing first column
for (let i = 1; i < n; i++) { for (let i = 1; i < n; i++) {
matrix[i][0] += matrix[i - 1][0] for (let j = 1; j < m; j++) { moves[i][j] = Math.min(moves[i - 1][j], moves[i][j - 1]) + matrix[i][j] }
} }
// Updating cost to current position return moves[n - 1][m - 1]
for (let i = 1; i < n; i++) {
for (let j = 1; j < m; j++) {
matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i][j - 1])
}
}
return matrix[n - 1][m - 1]
} }
const main = () => { const main = () => {
console.log(minCostPath([[2, 1], [3, 1], [4, 2]])) console.log(
console.log(minCostPath([[2, 1, 4], [2, 1, 3], [3, 2, 1]])) minCostPath([
[2, 1],
[3, 1],
[4, 2]
])
)
console.log(
minCostPath([
[2, 1, 4],
[2, 1, 3],
[3, 2, 1]
])
)
} }
main() main()