2087. Minimum Cost Homecoming of a Robot in a Grid

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
int ret = 0;
int i = startPos[0], j = startPos[1], x = homePos[0], y = homePos[1];

if(i<x){
for(int c = i+1 ; c<=x;++c) ret+=rowCosts[c];
}
else if(i>x){
for(int c = i-1;c>=x;--c) ret+=rowCosts[c];
}
if(j<y){
for(int c = j+1;c<=y;++c) ret+=colCosts[c];
}
else if(j>y){
for(int c = j-1;c>=y;--c) ret+=colCosts[c];
}
return ret;
}
};

analysis

  • time complexity O(nm)
  • space complexity O(1)