Given a m x ngrid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.
Example 2:
Input: grid = [[1,2,3],[4,5,6]]
Output: 12
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 200
Solutions
Solution 1: Dynamic Programming
Thinking
The first idea is to enumerate every path from the top left to the bottom right and take the smallest sum. \(m, n \le 200\), so the number of paths is exponential.
The bottleneck is recomputing overlapping prefixes. We may only move right or down, so the optimum into \((i, j)\) is the better of the cell above and the cell to the left, plus the current value.
Store that minimum in \(f[i][j]\): the borders accumulate along a single edge; the interior takes a \(\min\) then adds \(\textit{grid}[i][j]\). Fill by rows; the bottom-right cell is the answer.
We define \(f[i][j]\) to represent the minimum path sum from the top left corner to \((i, j)\). Initially, \(f[0][0] = grid[0][0]\), and the answer is \(f[m - 1][n - 1]\).
Consider \(f[i][j]\):
If \(j = 0\), then \(f[i][j] = f[i - 1][j] + grid[i][j]\);
If \(i = 0\), then \(f[i][j] = f[i][j - 1] + grid[i][j]\);
If \(i > 0\) and \(j > 0\), then \(f[i][j] = \min(f[i - 1][j], f[i][j - 1]) + grid[i][j]\).
Finally, return \(f[m - 1][n - 1]\).
The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Here, \(m\) and \(n\) are the number of rows and columns of the grid, respectively.