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

原题

一、直接法

只要起点和终点确定,则cost就确定,并不涉及dp

class Solution:
    def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:
        cost = 0
        sx, sy = startPos
        hx, hy = homePos
        # 只需考虑起点与终点的横纵坐标关系
        if sx < hx:
            cost += sum(rowCosts[sx+1:hx+1])
        else:
            cost += sum(rowCosts[hx:sx])
        if sy < hy:
            cost += sum(colCosts[sy+1:hy+1])
        else:
            cost += sum(colCosts[hy:sy])
        
        return cost

最后更新于