Min Cost PathProblem

Pattern: 2D grid DP

medium

Moving right, down or diagonally down-right from the top-left to the bottom-right, the cheapest way to a cell is its cost plus the cheapest of the three cells you can arrive from.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a cost grid, return the least total cost from the top-left cell to the bottom-right cell, moving right, down or diagonally down-right; both end cells are counted. The catalogue has no practice link for this one.

Think first

  • From which cells can you reach (r, c)?
  • What is the cost of the first cell?
  • Why not Dijkstra?

Hints

    Brute force, and why it fails

    Try every path: exponential.

    The key insight

    Moves never go back, so filling row by row gives each cell its final best value.

    Dry run

    cost [[1, 2, 3], [4, 8, 2], [1, 5, 3]]. Row 0: 1 3 6. Row 1: 5, 9, 5.

    Step 1 of 2

    The plan

    best[r][c] = cost[r][c] + min(best above, left, diagonal)
    

    Complexity

    Time
    O(R × C)
    Space
    O(R × C)

    Each cell once.

    Edge cases

    • 1 × 1.
    • One row.
    • Diagonal shortcuts.
    I've built my logic, show the code

    Java

    class Solution {
        public int minCostPath(int[][] cost) {
            int R = cost.length, C = cost[0].length;
            int[][] best = new int[R][C];           // best[r][c]: the cheapest way from (0, 0) to (r, c)
            for (int r = 0; r < R; r++)
                for (int c = 0; c < C; c++) {
                    int m = Integer.MAX_VALUE;      // arrive from above, from the left or diagonally
                    if (r > 0) m = Math.min(m, best[r - 1][c]);
                    if (c > 0) m = Math.min(m, best[r][c - 1]);
                    if (r > 0 && c > 0) m = Math.min(m, best[r - 1][c - 1]);
                    best[r][c] = cost[r][c] + (m == Integer.MAX_VALUE ? 0 : m);
                }
            return best[R - 1][C - 1];
        }
    }

    C++

    class Solution {
    public:
        int minCostPath(vector<vector<int>>& cost) {
            int R = static_cast<int>(cost.size()), C = static_cast<int>(cost[0].size());
            vector<vector<int>> best(R, vector<int>(C, 0));   // best[r][c]: the cheapest way from (0, 0) to (r, c)
            for (int r = 0; r < R; r++)
                for (int c = 0; c < C; c++) {
                    int m = INT_MAX;                // arrive from above, from the left or diagonally
                    if (r > 0) m = min(m, best[r - 1][c]);
                    if (c > 0) m = min(m, best[r][c - 1]);
                    if (r > 0 && c > 0) m = min(m, best[r - 1][c - 1]);
                    best[r][c] = cost[r][c] + (m == INT_MAX ? 0 : m);
                }
            return best[R - 1][C - 1];
        }
    };

    Python

    class Solution:
        def minCostPath(self, cost: list[list[int]]) -> int:
            R, C = len(cost), len(cost[0])
            best = [[0] * C for _ in range(R)]      # best[r][c]: the cheapest way from (0, 0) to (r, c)
            for r in range(R):
                for c in range(C):
                    options = [best[r - 1][c]] if r else []   # arrive from above, from the left or diagonally
                    if c:
                        options.append(best[r][c - 1])
                    if r and c:
                        options.append(best[r - 1][c - 1])
                    best[r][c] = cost[r][c] + (min(options) if options else 0)
            return best[-1][-1]

    Common mistakes

    • Allowing up or left moves.
    • Missing the diagonal.

    Similar problems