Algo-Sim › Dynamic Programming

Minimum Path Sum

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Cheapest right/down path through a grid of costs: each cell adds its cost to the cheaper of the cell above and the cell to its left, in one rolling row.

Problem

You are given an m × n grid of non-negative numbers. Moving only right or down from the top-left cell to the bottom-right cell, the cost of a path is the sum of every cell it visits. Return the smallest possible cost.

Constraints

Edge cases to test

Follow-up questions

Can it be done in place?
Yes, if you may overwrite the grid: each cell becomes its best path cost. O(mn) time, O(1) extra.
What if moves can go in any direction?
Then it is a shortest path with non-negative weights: Dijkstra, O(mn log mn).

Solution

Java

public int minPathSum(int[][] grid) {
    int m = grid.length, n = grid[0].length;
    int[] dp = new int[n];
    for (int r = 0; r < m; r++) {
        for (int c = 0; c < n; c++) {
            if (r == 0 && c == 0) dp[c] = grid[0][0];
            else if (r == 0) dp[c] = dp[c - 1] + grid[r][c];
            else if (c == 0) dp[c] = dp[c] + grid[r][c];
            else dp[c] = Math.min(dp[c], dp[c - 1]) + grid[r][c];
        }
    }
    return dp[n - 1];
}

Python

def min_path_sum(grid):
    m, n = len(grid), len(grid[0])
    dp = [0] * n
    for r in range(m):
        for c in range(n):
            if r == 0 and c == 0: dp[c] = grid[0][0]
            elif r == 0: dp[c] = dp[c - 1] + grid[r][c]
            elif c == 0: dp[c] = dp[c] + grid[r][c]
            else: dp[c] = min(dp[c], dp[c - 1]) + grid[r][c]
    return dp[n - 1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minPathSum(vector<vector<int>> &grid) {
        int m = int(grid.size()), n = int(grid[0].size());
        vector<int> dp(n);
        for (int r = 0; r < m; r++) {
            for (int c = 0; c < n; c++) {
                if (r == 0 && c == 0)
                    dp[c] = grid[0][0];
                else if (r == 0)
                    dp[c] = dp[c - 1] + grid[r][c];
                else if (c == 0)
                    dp[c] = dp[c] + grid[r][c];
                else
                    dp[c] = min(dp[c], dp[c - 1]) + grid[r][c];
            }
        }
        return dp[n - 1];
    }
};

More Dynamic Programming problems