Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the minimum path sum in a grid

Compute the smallest sum along a path from top-left to bottom-right of a grid moving only right or down.

Python practice15 minDynamic ProgrammingIntermediateLast updated March 29, 2026

Problem statement

Given a 2D grid of non-negative integers, return the minimum sum of values along a path from the top-left cell to the bottom-right cell. You may only move either down or right at any point in time. Use dynamic programming to compute the result efficiently.

Task

Practice dynamic programming by computing minimum path sums using a bottom-up DP table.

Examples

Example

Input

min_path_sum([[1,3,1],[1,5,1],[4,2,1]])

Output

7

One minimum path is 1 → 3 → 1 → 1 → 1 (sum = 7).

Input format

A single argument: grid, a list of lists of non-negative integers representing the matrix.

Output format

An integer representing the minimum path sum from top-left to bottom-right.

Constraints

1 <= number of rows, number of columns <= 100. Grid values are non-negative integers that fit in a 32-bit signed integer when summed within constraints.

Samples

Sample 1

Input

min_path_sum([[1,2],[3,4]])

Output

7

Path 1 → 2 → 4 gives sum 7.