[LeetCode] Minimum Cost Homecoming of a Robot in a Grid

2087. Minimum Cost Homecoming of a Robot in a Grid

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 = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
int y = startPos[0], x = startPos[1], gy = homePos[0], gx = homePos[1];
int res = 0;
if(y > gy) for(int i = y - 1; i >= gy; i--) res += rowCosts[i];
else for(int i = y + 1; i <= gy; i++) res += rowCosts[i];
if(x > gx) for(int i = x - 1; i >= gx; i--) res += colCosts[i];
else for(int i = x + 1; i <= gx; i++) res += colCosts[i];
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/21/PS/LeetCode/minimum-cost-homecoming-of-a-robot-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.