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。