Leetcode 3342. Find Minimum Time to Reach Last Room II

1. 解题思路

这一题算是一个比较常规的套路题,和题目3341基本完全一样,就是使用一个堆排按照最小到达时间不断延拓从 ( 0 , 0 ) (0,0) (0,0)开始到达其他点的最小时间。

2. 代码实现

给出python代码实现如下:

class Solution:
    def minTimeToReach(self, moveTime: List[List[int]]) -> int:
        n, m = len(moveTime), len(moveTime[0])
        q = [(0, 1, 0, 0)]
        seen = set()
        ans = math.inf
        while q != []:
            t, dt, x, y = heapq.heappop(q)
            if x == n-1 and y == m-1:
                return t
            if (x, y) in seen:
                continue
            seen.add((x, y))
            if x-1 >= 0 and (x-1, y) not in seen:
                heapq.heappush(q, (max(t, moveTime[x-1][y])+dt, 3-dt, x-1, y))
            if x+1 < n and (x+1, y) not in seen:
                heapq.heappush(q, (max(t, moveTime[x+1][y])+dt, 3-dt, x+1, y))
            if y-1 >= 0 and (x, y-1) not in seen:
                heapq.heappush(q, (max(t, moveTime[x][y-1])+dt, 3-dt, x, y-1))
            if y+1 < m and (x, y+1) not in seen:
                heapq.heappush(q, (max(t, moveTime[x][y+1])+dt, 3-dt, x, y+1))
        return -1

提交代码评测得到:耗时2612ms,占用内存163MB。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值