走直线就对了,不需要拐弯抹角
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;
}
}
最后
以上就是俏皮身影最近收集整理的关于2087. 网格图中机器人回家的最小代价的全部内容,更多相关2087.内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复