Skip to content
BytePatterns

Cheapest Path Across a Grid

EasyDynamic Programming#grid-dp#2d-dp~20m

Problem

A grid holds a non-negative cost in every cell. You start in the top-left cell and must reach the bottom-right cell, moving only right or down. Return the smallest possible sum of the costs of the cells you pass through, including the first and last cells.

Examples

Input:  grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]]
Output: 7
Why:    right, right, down, down visits 1, 3, 1, 1, 1 and avoids the 5 in the middle
Input:  grid = [[2, 1, 4], [3, 1, 1]]
Output: 5
Why:    right, down, right visits 2, 1, 1, 1
Input:  grid = [[7]]
Output: 7
Why:    edge case, the start is also the finish

Hints

0 / 3

Stuck on the idea rather than the code? DP on Grids covers it.