Leetcode 2087: Minimum Cost Homecoming of a Robot in a Grid

grid47
grid47
Exploring patterns and algorithms
Apr 12, 2024 6 min read

You are given a grid of size m x n and two positions: the robot’s starting position (startPos) and its home position (homePos). The robot can move left, right, up, or down, with associated costs for moving to new rows and columns. Calculate the minimum total cost for the robot to move from its start position to its home position.
Problem
Approach
Steps
Complexity
Input: You are given two integer arrays: startPos and homePos, both of length 2. Additionally, you are given two arrays: rowCosts of length m and colCosts of length n, representing the costs for moving to different rows and columns respectively.
Example: [1, 2], [3, 4], [5, 6]
Constraints:
• 1 <= m, n <= 10^5
• 0 <= rowCosts[r], colCosts[c] <= 10^4
• 0 <= startPos[0], homePos[0] < m
• 0 <= startPos[1], homePos[1] < n
Output: Return the minimum cost for the robot to travel from startPos to homePos. If no movement is required, return 0.
Example: 20
Constraints:
• The robot must always move within the grid boundaries.
Goal: The goal is to compute the minimum cost for the robot to move from its starting position to its home, considering the costs for moving to different rows and columns.
Steps:
• Calculate the row-wise and column-wise movements needed to reach from startPos to homePos.
• Sum up the movement costs based on rowCosts and colCosts arrays for the respective movements.
• If the robot is already at homePos, return 0.
Goal: The grid can be large (up to 100,000 x 100,000). Ensure that the solution works efficiently for large inputs.
Steps:
• 1 <= m, n <= 10^5
• 0 <= rowCosts[r], colCosts[c] <= 10^4
• startPos and homePos are within grid bounds.
Assumptions:
• The robot's startPos and homePos are valid and within the grid.
• The cost arrays (rowCosts and colCosts) are properly aligned with the grid size.
Input: [2, 1], [0, 3], [4, 2, 3], [5, 3, 6, 7]
Explanation: To go from (2, 1) to (0, 3), the robot needs to move up, incurring a row cost of 2, and then move right twice, incurring a column cost of 6 and 7 respectively. The total cost is 2 + 6 + 7 = 20.

Link to LeetCode Lab


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