EasyPythonJavaScriptTypeScript
DP — Minimum Path Sum
AlgorithmsDynamic ProgrammingMatrix
solve(grid) — grid holds non-negative numbers. Starting at the top-left cell,
move only right or down to reach the bottom-right cell. Return the smallest
possible sum of the numbers along a path (both end cells included).
best[r][c] = grid[r][c] + min(best[r-1][c], best[r][c-1]) — each cell is reached
from above or from the left, so the cheapest path to it extends the cheaper of the
two.
Examples
solve([[1,3,1],[1,5,1],[4,2,1]]) → 7 // 1 → 3 → 1 → 1 → 1
solve([[1,2,3],[4,5,6]]) → 12
solve([[5]]) → 5Sample tests
Test #1Classic example
Input: [[[1,3,1],[1,5,1],[4,2,1]]]
Output: 7
Test #2Two rows
Input: [[[1,2,3],[4,5,6]]]
Output: 12
Test #3Single cell
Input: [[[5]]]
Output: 5