|
1 |
| -// youtube Link -> https://www.youtube.com/watch?v=lBRtnuxg-gU |
| 1 | +// Problem Statement => https://www.youtube.com/watch?v=lBRtnuxg-gU |
2 | 2 |
|
3 | 3 | const minCostPath = (matrix) => {
|
4 | 4 | /*
|
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 | + |
9 | 10 | const n = matrix.length
|
10 | 11 | const m = matrix[0].length
|
11 | 12 |
|
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) |
16 | 16 |
|
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] |
21 | 21 |
|
22 |
| - // Updating cost to current position |
23 | 22 | 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] } |
27 | 24 | }
|
28 | 25 |
|
29 |
| - return matrix[n - 1][m - 1] |
| 26 | + return moves[n - 1][m - 1] |
30 | 27 | }
|
31 | 28 |
|
32 | 29 | 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 | + ) |
35 | 44 | }
|
36 | 45 |
|
37 | 46 | main()
|
0 commit comments