Skip to content

Commit 80c2dc8

Browse files
authored
Merge pull request #551 from DhruvGheewala/master
Update MinimumCostPath.js
2 parents 499c96c + 902b1df commit 80c2dc8

File tree

1 file changed

+29
-20
lines changed

1 file changed

+29
-20
lines changed
Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,46 @@
1-
// youtube Link -> https://www.youtube.com/watch?v=lBRtnuxg-gU
1+
// Problem Statement => https://www.youtube.com/watch?v=lBRtnuxg-gU
22

33
const minCostPath = (matrix) => {
44
/*
5-
Find the min cost path from top-left to bottom-right in matrix
6-
>>> minCostPath([[2, 1], [3, 1], [4, 2]])
7-
6
8-
*/
5+
Find the min cost path from top-left to bottom-right in matrix
6+
>>> minCostPath([[2, 1], [3, 1], [4, 2]])
7+
>>> 6
8+
*/
9+
910
const n = matrix.length
1011
const m = matrix[0].length
1112

12-
// Preprocessing first row
13-
for (let i = 1; i < m; i++) {
14-
matrix[0][i] += matrix[0][i - 1]
15-
}
13+
// moves[i][j] => minimum number of moves to reach cell i, j
14+
const moves = new Array(n)
15+
for (let i = 0; i < moves.length; i++) moves[i] = new Array(m)
1616

17-
// Preprocessing first column
18-
for (let i = 1; i < n; i++) {
19-
matrix[i][0] += matrix[i - 1][0]
20-
}
17+
// base conditions
18+
moves[0][0] = matrix[0][0] // to reach cell (0, 0) from (0, 0) is of no moves
19+
for (let i = 1; i < m; i++) moves[0][i] = moves[0][i - 1] + matrix[0][i]
20+
for (let i = 1; i < n; i++) moves[i][0] = moves[i - 1][0] + matrix[i][0]
2121

22-
// Updating cost to current position
2322
for (let i = 1; i < n; i++) {
24-
for (let j = 1; j < m; j++) {
25-
matrix[i][j] += Math.min(matrix[i - 1][j], matrix[i][j - 1])
26-
}
23+
for (let j = 1; j < m; j++) { moves[i][j] = Math.min(moves[i - 1][j], moves[i][j - 1]) + matrix[i][j] }
2724
}
2825

29-
return matrix[n - 1][m - 1]
26+
return moves[n - 1][m - 1]
3027
}
3128

3229
const main = () => {
33-
console.log(minCostPath([[2, 1], [3, 1], [4, 2]]))
34-
console.log(minCostPath([[2, 1, 4], [2, 1, 3], [3, 2, 1]]))
30+
console.log(
31+
minCostPath([
32+
[2, 1],
33+
[3, 1],
34+
[4, 2]
35+
])
36+
)
37+
console.log(
38+
minCostPath([
39+
[2, 1, 4],
40+
[2, 1, 3],
41+
[3, 2, 1]
42+
])
43+
)
3544
}
3645

3746
main()

0 commit comments

Comments
 (0)