Minimum Path Cost in a Grid — LeetCode 2304 Python Solution

MediumArrayDynamic ProgrammingMatrix
Problem
#2304
Reading time
2 min

The problem

You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row.

Example

Input
grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]
Output
17
Explanation
The path with the minimum possible cost is the path 5 -> 0 -> 1.

Python solution

Python
class Solution:
    def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        f = grid[0]
        for i in range(1, m):
            g = [inf] * n
            for j in range(n):
                for k in range(n):
                    g[j] = min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j])
            f = g
        return min(f)

Complexity

MeasureComplexity
TimeO(m \times n^2)
SpaceO(n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2304. Minimum Path Cost in a Grid is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2304. Minimum Path Cost in a Grid?
LeetCode 2304. Minimum Path Cost in a Grid is rated Medium on LeetCode.
What is the time complexity of LeetCode 2304. Minimum Path Cost in a Grid?
The Python solution on this page runs in O(m \times n^2).
What is the space complexity of LeetCode 2304. Minimum Path Cost in a Grid?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2304. Minimum Path Cost in a Grid cover?
LeetCode 2304. Minimum Path Cost in a Grid is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview