leetcode 2087. 网格图中机器人回家的最小代价 中等

给你一个 m x n 的网格图,其中 (0, 0) 是最左上角的格子,(m - 1, n - 1) 是最右下角的格子。给你一个整数数组 startPos ,startPos = [startrow, startcol] 表示 初始 有一个 机器人 在格子 (startrow, startcol) 处。同时给你一个整数数组 homePos ,homePos = [homerow, homecol] 表示机器人的 家 在格子 (homerow, homecol) 处。

机器人需要回家。每一步它可以往四个方向移动:上 ,下 ,左 ,右 ,同时机器人不能移出边界。每一步移动都有一定代价。再给你两个下标从 0 开始的整数数组:长度为 m 的数组 rowCosts 和长度为 n 的数组 colCosts 。

  • 如果机器人往 上 或者往 下 移动到第 r 行 的格子,那么代价为 rowCosts[r] 。
  • 如果机器人往 左 或者往 右 移动到第 c 列 的格子,那么代价为 colCosts[c] 。

请你返回机器人回家需要的 最小总代价 。

示例 1:

复制代码
输入:startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]
输出:18
解释:一个最优路径为:
从 (1, 0) 开始
-> 往下走到 (2, 0) 。代价为 rowCosts[2] = 3 。
-> 往右走到 (2, 1) 。代价为 colCosts[1] = 2 。
-> 往右走到 (2, 2) 。代价为 colCosts[2] = 6 。
-> 往右走到 (2, 3) 。代价为 colCosts[3] = 7 。
总代价为 3 + 2 + 6 + 7 = 18

示例 2:

复制代码
输入:startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]
输出:0
解释:机器人已经在家了,所以不需要移动。总代价为 0 。

提示:

  • 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 <= startrow, homerow < m
  • 0 <= startcol, homecol < n

分析:机器人回家的最短路径就是走两条线段:先走到家的那一行,再走到家的那一列,或者先走列,再走行,不用考虑绕路或者其它方法。计算机器人从 startrow 移动到 homerow 的代价,加上人从 startcol 移动到 homecol 的代价即可。

cpp 复制代码
class Solution {
public:
    int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
        int ans=0;
        int f=startPos[0]>homePos[0]?-1:1;
        for(int i=startPos[0];i!=homePos[0];i+=f)
            ans+=rowCosts[i+f];
        f=startPos[1]>homePos[1]?-1:1;
        for(int i=startPos[1];i!=homePos[1];i+=f)
            ans+=colCosts[i+f];
        return ans;
    }
};
相关推荐
j7~10 小时前
【穷举、深搜与回溯算法】一棵决策树讲透全排列与子集
数据结构·c++·算法·leetcode·回溯·递归
Shaoshing11 小时前
LeetCode100 42.接雨水
java·算法·leetcode
文丑颜不良啊13 小时前
LeetCode1261~1280题目解析
java·leetcode
Shaoshing13 小时前
LeetCode100 11. 盛最多水的容器
算法·leetcode
海绵宝宝转agent14 小时前
Leetcode二叉树算法个人理解
笔记·学习·算法·leetcode·深度优先
Rain的Java大神之路14 小时前
面试被LeetCode 27(移除元素)问懵?别再用两层 for 循环了:一道“简单题”吃透双指针原地删除,附面试加分话术 + 11 个避坑清单
后端·leetcode·面试
重生之小比特16 小时前
【算法拾光】前缀和|连续的子数组和 + 和相同的二元子数组
算法·leetcode·哈希算法
Pniubi16 小时前
力扣 102二叉树的层序遍历(广度优先搜索)
leetcode·宽度优先
一去不复返的通信er16 小时前
力扣15:盛最多水的容器
算法·leetcode
Navigator_Z16 小时前
LeetCode //C - 1309. Decrypt String from Alphabet to Integer Mapping
c语言·算法·leetcode