Overview
This is a variation of Grid Unique Paths, but instead of counting ways, we want to optimize a cost function (the sum of values).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find a path from top-left to bottom-right in a grid, moving only down or right, which minimizes the sum of all numbers along its path.
This is a variation of Grid Unique Paths, but instead of counting ways, we want to optimize a cost function (the sum of values).
Since you can only move down or right, the cell `(r, c)` can only be entered from `(r-1, c)` (top) or `(r, c-1)` (left). To minimize the total cost at `(r, c)`, you must choose the minimum of those two entry paths.
The top boundary can only be reached by moving right. The left boundary can only be reached by moving down. We prefill these to avoid out-of-bounds checks in the main loop.
Since we only look at the current row and the row above it, we can optimize space to O(N) by keeping just two 1D arrays, or mutating the original grid.