Minimum Cost Homecoming of a Robot in a Grid Problem
Description
LeetCode Problem 2087.
There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [start_row, start_col] indicates that initially, a robot is at the cell (start_row, start_col). You are also given an integer array homePos where homePos = [home_row, home_col] indicates that its home is at the cell (home_row, home_col).
The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.
- If the robot moves up or down into a cell whose row is
r, then this move costsrowCosts[r]. - If the robot moves left or right into a cell whose column is
c, then this move costscolCosts[c].
Return the minimum total cost for this robot to return home.
Example 1:

Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]
Output: 18
Explanation: One optimal path is that:
Starting from (1, 0)
-> It goes down to (2, 0). This move costs rowCosts[2] = 3.
-> It goes right to (2, 1). This move costs colCosts[1] = 2.
-> It goes right to (2, 2). This move costs colCosts[2] = 6.
-> It goes right to (2, 3). This move costs colCosts[3] = 7.
The total cost is 3 + 2 + 6 + 7 = 18
Example 2:
Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]
Output: 0
Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.
Constraints:
m == rowCosts.lengthn == colCosts.length1 <= m, n <= 10^50 <= rowCosts[r], colCosts[c] <= 10^4startPos.length == 2homePos.length == 20 <= start_row, home_row < m0 <= start_col, home_col < n
Solution
Approach: Greedy, Sum the Rows and Columns Crossed
Every path from the start to home must enter each row between them and each column between them at least once, and a monotone path enters each exactly once, so the cheapest cost is fixed.
Let the start be (x0, y0) and home be (x1, y1).
- Vertical cost: if
x0 < x1, addrowCosts[x0 + 1 .. x1]; ifx0 > x1, addrowCosts[x1 .. x0 - 1]; otherwise0. (We pay for the row we enter, never the one we leave.) - Horizontal cost: the same with
colCostsandy0,y1.
The answer is the sum of both.
Complexity: Time O(m + n), space O(1).
class Solution:
def minCost(
self,
startPos: List[int],
homePos: List[int],
rowCosts: List[int],
colCosts: List[int],
) -> int:
x0, y0 = startPos
x1, y1 = homePos
dx = sum(rowCosts[x0 + 1 : x1 + 1]) if x0 < x1 else sum(rowCosts[x1:x0])
dy = sum(colCosts[y0 + 1 : y1 + 1]) if y0 < y1 else sum(colCosts[y1:y0])
return dx + dy