Leetcode 2304: Minimum Path Cost in a Grid

grid47
grid47
Exploring patterns and algorithms
Mar 21, 2024 8 min read

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. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), …, (x + 1, n - 1). The move from cells in the last row can be ignored. Each possible move has a cost given by the moveCost matrix, where moveCost[i][j] represents the cost of moving from a cell with value i to a cell in column j of the next row.
Problem
Approach
Steps
Complexity
Input: The input consists of two matrices: grid and moveCost.
Example: grid = [[8, 2], [4, 7], [5, 9]]; moveCost = [[5, 4], [2, 6], [3, 5], [4, 2], [7, 8], [9, 1], [3, 2], [8, 9], [5, 6], [6, 7], [3, 2], [1, 4]]
Constraints:
• 2 <= m, n <= 50
• grid consists of distinct integers from 0 to m * n - 1.
• moveCost.length == m * n
• 1 <= moveCost[i][j] <= 100
Output: Return the minimum cost of a path from the first row to the last row.
Example: The output for the example grid = [[8, 2], [4, 7], [5, 9]] and moveCost = [[5, 4], [2, 6], [3, 5], [4, 2], [7, 8], [9, 1], [3, 2], [8, 9], [5, 6], [6, 7], [3, 2], [1, 4]] is 12.
Constraints:
Goal: Find the minimum cost path that starts from any cell in the first row and ends at any cell in the last row.
Steps:
• Start from each cell in the first row.
• For each cell, calculate the possible paths to all cells in the next row.
• Use dynamic programming (memoization) to store the minimum cost for each cell to avoid redundant calculations.
• Return the minimum cost path at the end.
Goal: The dimensions of the grid and moveCost matrices are constrained by the problem.
Steps:
• 2 <= m, n <= 50
• grid consists of distinct integers from 0 to m * n - 1.
• moveCost.length == m * n
• 1 <= moveCost[i][j] <= 100
Assumptions:
• You can start from any cell in the first row and end at any cell in the last row.
• The moveCost matrix defines the cost of moving from each cell to the cells in the next row.
Input: grid = [[8, 2], [4, 7], [5, 9]], moveCost = [[5, 4], [2, 6], [3, 5], [4, 2], [7, 8], [9, 1], [3, 2], [8, 9], [5, 6], [6, 7], [3, 2], [1, 4]]
Explanation: The minimum path cost is achieved by the path 8 -> 7 -> 9 with a total cost of 12.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus