zl程序教程

您现在的位置是:首页 >  硬件

当前栏目

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

机器人 最小 网格 代价 回家 图中
2023-09-14 09:01:26 时间

题目链接

Leetcode.2087 网格图中机器人回家的最小代价 Rating : 1744

题目描述

给你一个 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 < = 1 0 5 1 <= m, n <= 10^5 1<=m,n<=105
  • 0 < = r o w C o s t s [ r ] , c o l C o s t s [ c ] < = 1 0 4 0 <= rowCosts[r], colCosts[c] <= 10^4 0<=rowCosts[r],colCosts[c]<=104
  • s t a r t P o s . l e n g t h = = 2 startPos.length == 2 startPos.length==2
  • h o m e P o s . l e n g t h = = 2 homePos.length == 2 homePos.length==2
  • 0 < = s t a r t r o w , h o m e r o w < m 0 <= startrow, homerow < m 0<=startrow,homerow<m
  • 0 < = s t a r t c o l , h o m e c o l < n 0 <= startcol, homecol < n 0<=startcol,homecol<n

解法:贪心

如果从 startPos 到达 homePos 要经过 r1,r2,r3行,c1,c2,c3列。

无论 startPos 如何走,最终一定都会经过 r1,r2,r3行,c1,c2,c3列。

所以最优的方式就是直接走。

时间复杂度: O ( m n ) O(mn) O(mn)

C++代码:

class Solution {
public:
    int minCost(vector<int>& startPos, vector<int>& homePos, vector<int>& rowCosts, vector<int>& colCosts) {
        int ans = 0;
        if(startPos[0] < homePos[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(startPos[1] < homePos[1]){
            for(int j = startPos[1] + 1;j <= homePos[1];j++) ans += colCosts[j];
        }
        else{
            for(int j = startPos[1] - 1;j >= homePos[1];j--) ans += colCosts[j];
        }

        return ans;
    }
};