28 lines
1.1 KiB
Python
28 lines
1.1 KiB
Python
# https://leetcode.com/problems/find-minimum-time-to-reach-last-room-ii
|
|
|
|
from typing import List, Tuple
|
|
import heapq
|
|
|
|
class Solution:
|
|
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
|
|
n, m = len(moveTime), len(moveTime[0])
|
|
dirs: List[Tuple[int, int]] = [(-1, 0), (1, 0), (0, -1), (0, 1)]
|
|
min_time = [[float('inf')] * m for _ in range(n)]
|
|
min_time[0][0] = 0
|
|
heap: List[Tuple[int, int, int, int]] = [(0, 0, 0, 1)]
|
|
|
|
while heap:
|
|
curr_time, y, x, moves = heapq.heappop(heap)
|
|
if (y, x) == (n - 1, m - 1):
|
|
return curr_time
|
|
if curr_time > min_time[y][x]:
|
|
continue
|
|
for dy, dx in dirs:
|
|
ny, nx = y + dy, x + dx
|
|
if 0 <= ny < n and 0 <= nx < m:
|
|
start_time = max(curr_time, moveTime[ny][nx])
|
|
arrival_time = start_time + (2 if moves % 2 == 0 else 1)
|
|
if arrival_time < min_time[ny][nx]:
|
|
min_time[ny][nx] = arrival_time
|
|
heapq.heappush(heap, (arrival_time, ny, nx, moves + 1))
|
|
return -1
|