|
| 1 | +[](https://github.com/javadev/LeetCode-in-All) |
| 2 | +[](https://github.com/javadev/LeetCode-in-All/fork) |
| 3 | + |
| 4 | +## 64\. Minimum Path Sum |
| 5 | + |
| 6 | +Medium |
| 7 | + |
| 8 | +Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. |
| 9 | + |
| 10 | +**Note:** You can only move either down or right at any point in time. |
| 11 | + |
| 12 | +**Example 1:** |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +**Input:** grid = \[\[1,3,1],[1,5,1],[4,2,1]] |
| 17 | + |
| 18 | +**Output:** 7 |
| 19 | + |
| 20 | +**Explanation:** Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum. |
| 21 | + |
| 22 | +**Example 2:** |
| 23 | + |
| 24 | +**Input:** grid = \[\[1,2,3],[4,5,6]] |
| 25 | + |
| 26 | +**Output:** 12 |
| 27 | + |
| 28 | +**Constraints:** |
| 29 | + |
| 30 | +* `m == grid.length` |
| 31 | +* `n == grid[i].length` |
| 32 | +* `1 <= m, n <= 200` |
| 33 | +* `0 <= grid[i][j] <= 100` |
| 34 | + |
| 35 | +## Solution |
| 36 | + |
| 37 | +```javascript |
| 38 | +/** |
| 39 | + * @param {number[][]} grid |
| 40 | + * @return {number} |
| 41 | + */ |
| 42 | +var minPathSum = function(grid) { |
| 43 | + const rows = grid.length |
| 44 | + const cols = grid[0].length |
| 45 | + |
| 46 | + // Handle the special case where grid has only one cell |
| 47 | + if (rows === 1 && cols === 1) { |
| 48 | + return grid[0][0] |
| 49 | + } |
| 50 | + |
| 51 | + // Create a 2D array for dynamic programming |
| 52 | + const dm = Array.from({ length: rows }, () => Array(cols).fill(0)) |
| 53 | + |
| 54 | + // Initialize the last column |
| 55 | + let s = 0 |
| 56 | + for (let r = rows - 1; r >= 0; r--) { |
| 57 | + dm[r][cols - 1] = grid[r][cols - 1] + s |
| 58 | + s += grid[r][cols - 1] |
| 59 | + } |
| 60 | + |
| 61 | + // Initialize the last row |
| 62 | + s = 0 |
| 63 | + for (let c = cols - 1; c >= 0; c--) { |
| 64 | + dm[rows - 1][c] = grid[rows - 1][c] + s |
| 65 | + s += grid[rows - 1][c] |
| 66 | + } |
| 67 | + |
| 68 | + // Recursive helper function |
| 69 | + const recur = (r, c) => { |
| 70 | + if ( |
| 71 | + dm[r][c] === 0 && |
| 72 | + r !== rows - 1 && |
| 73 | + c !== cols - 1 |
| 74 | + ) { |
| 75 | + dm[r][c] = |
| 76 | + grid[r][c] + |
| 77 | + Math.min( |
| 78 | + recur(r + 1, c), |
| 79 | + recur(r, c + 1) |
| 80 | + ) |
| 81 | + } |
| 82 | + return dm[r][c] |
| 83 | + } |
| 84 | + |
| 85 | + // Start recursion from the top-left corner |
| 86 | + return recur(0, 0) |
| 87 | +}; |
| 88 | + |
| 89 | +export { minPathSum } |
| 90 | +``` |
0 commit comments