走直线就对了,不需要拐弯抹角
class Solution {
public int minCost(int[] startPos, int[] homePos, int[] rowCosts, int[] colCosts) {
int x = startPos[0] - homePos[0];
int y = startPos[1] - homePos[1];
int ans = 0;
// 计算机器人横向走的代价
if (x < 0){
// 计算到家的距离,直接走直线
for (int i = startPos[0] + 1; i <= homePos[0]; i++){
ans += rowCosts[i];
}
} else {
for (int i = startPos[0] - 1; i >= homePos[0]; i--){
ans += rowCosts[i];
}
}
// 计算机器人纵向走的代价
if (y < 0){
for (int i = startPos[1] + 1; i <= homePos[1]; i++){
ans += colCosts[i];
}
} else {
for (int i = startPos[1] - 1; i >= homePos[1]; i--){
ans += colCosts[i];
}
}
return ans;
}
}