# https://leetcode.com/problems/find-minimum-time-to-reach-last-room-i import heapq from typing import List, Tuple 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]] = [(0, 0, 0)] while heap: curr_time, y, x = 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 + 1 if arrival_time < min_time[ny][nx]: min_time[ny][nx] = arrival_time heapq.heappush(heap, (arrival_time, ny, nx)) return -1