Problem Description
Given an m x n grid filled with non-negative numbers, find a path from the top-left cell to the bottom-right cell that minimizes the sum of all numbers along its path. You can only move either down or right at any point.
Key Insights
- The problem can be solved using Dynamic Programming.
- The optimal solution for each cell depends on the minimum path sum of the cell above it and the cell to its left.
- Since you can only move right or down, only two adjacent cells affect the current cell's result.
- Edge cases include the first row and first column, which have only one direction of movement.
Space and Time Complexity
Time Complexity: O(m * n), where m and n are the number of rows and columns. Space Complexity: O(m * n) for the DP table (this can be optimized to O(n) with in-place computations).
Solution
We use a Dynamic Programming (DP) approach where we create a DP table (or use the grid itself) that stores the minimum path sum to each cell. For each cell (i, j):
- If i = 0 (first row), the only possible path is from the left.
- If j = 0 (first column), the only possible path is from above.
- For other cells, the minimum path sum is the cell value plus the minimum of the two possible previous cells (above and left). This ensures that by the time we reach the bottom-right cell, we have accumulated the minimum sum required to reach that cell.