3627. Find Minimum Time to Reach Last Room I
My accepted Python solution to LeetCode problem 3627, Find Minimum Time to Reach Last Room I, running in 135ms.
- Difficulty: Medium
- Python
- Runtime 135ms
- Memory 17.9MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 135ms, memory 17.9MB, accepted 2025-12-31.
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
import heapq
n, m = len(moveTime), len(moveTime[0])
dist = [[float('inf')] * m for _ in range(n)]
dist[0][0] = 0
pq = [(0, 0, 0)] # (time, row, col)
while pq:
t, r, c = heapq.heappop(pq)
if r == n - 1 and c == m - 1:
return t
if t > dist[r][c]:
continue
for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < m:
# Wait until moveTime[nr][nc] if necessary, then move (1 sec)
new_time = max(t, moveTime[nr][nc]) + 1
if new_time < dist[nr][nc]:
dist[nr][nc] = new_time
heapq.heappush(pq, (new_time, nr, nc))
return dist[n-1][m-1]