Formatted question description: https://leetcode.ca/all/2087.html

# 2087. Minimum Cost Homecoming of a Robot in a Grid (Medium)

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`

indicates that _{row}, start_{col}]**initially**, a **robot** is at the cell `(start`

. You are also given an integer array _{row}, start_{col})`homePos`

where `homePos = [home`

indicates that its _{row}, home_{col}]**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 costs`rowCosts[r]`

. - If the robot moves
**left**or**right**into a cell whose**column**is`c`

, then this move costs`colCosts[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:18Explanation:One optimal path is that: Starting from (1, 0) -> It goes down to (, 0). This move costs rowCosts[2] = 3. -> It goes right to (2,2). This move costs colCosts[1] = 2. -> It goes right to (2,1). This move costs colCosts[2] = 6. -> It goes right to (2,2). This move costs colCosts[3] = 7. The total cost is 3 + 2 + 6 + 7 = 183

**Example 2:**

Input:startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]Output:0Explanation:The robot is already at its home. Since no moves occur, the total cost is 0.

**Constraints:**

`m == rowCosts.length`

`n == colCosts.length`

`1 <= m, n <= 10`

^{5}`0 <= rowCosts[r], colCosts[c] <= 10`

^{4}`startPos.length == 2`

`homePos.length == 2`

`0 <= start`

_{row}, home_{row}< m`0 <= start`

_{col}, home_{col}< n

**Similar Questions**:

- Unique Paths (Medium)
- Minimum Path Sum (Medium)
- Bomb Enemy (Medium)
- Count Square Submatrices with All Ones (Medium)

## Solution 1.

```
// OJ: https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/
// Time: O(X + Y) where `X`/`Y` is the absolute difference between the `x`/`y` values of the `startPos` and `homePos`
// Space: O(1)
class Solution {
public:
int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
int dx = homePos[0] > startPos[0] ? 1 : -1, dy = homePos[1] > startPos[1] ? 1 : -1, x = startPos[0], y = startPos[1], ans = 0;
while (x != homePos[0]) ans += rowCosts[x += dx];
while (y != homePos[1]) ans += colCosts[y += dy];
return ans;
}
};
```