Find Minimum Time to Reach Last Room I Problem
Description
LeetCode Problem 3341.
There is a dungeon with n x m rooms arranged as a grid.
You are given a 2D array moveTime of size n x m, where moveTime[i][j] represents the minimum time in seconds after which the room opens and can be moved to. You start from the room (0, 0) at time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes exactly one second.
Return the minimum time to reach the room (n - 1, m - 1).
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
Example 1:
Input: moveTime = [[0,4],[4,4]]
Output: 6
Explanation:
The minimum time required is 6 seconds.
- At time t == 4, move from room (0, 0) to room (1, 0) in one second.
- At time t == 5, move from room (1, 0) to room (1, 1) in one second.
Example 2:
Input: moveTime = [[0,0,0],[0,0,0]]
Output: 3
Explanation:
The minimum time required is 3 seconds.
- At time t == 0, move from room (0, 0) to room (1, 0) in one second.
- At time t == 1, move from room (1, 0) to room (1, 1) in one second.
- At time t == 2, move from room (1, 1) to room (1, 2) in one second.
Example 3:
Input: moveTime = [[0,1],[1,2]]
Output: 3
Constraints:
2 <= n == moveTime.length <= 502 <= m == moveTime[i].length <= 500 <= moveTime[i][j] <= 10^9
Solution
Approach: Dijkstra's algorithm
Treat each room as a graph node and each move as an edge whose cost depends on when we arrive. Moving always takes one second.
Keep dist[i][j], the earliest time we can be in room (i, j), starting with 0 at (0, 0) and infinity elsewhere, and a min-heap of (time, i, j). Pop the smallest entry, skip it if it is stale (its time is larger than dist), and return the time when it is the last room. For each neighbour (x, y) we have to wait until the neighbour opens at moveTime[x][y], so the arrival time is max(moveTime[x][y], d) + 1; if it improves dist[x][y], store it and push it. Waiting never hurts later moves, so the earliest arrival is always the best one.
Complexity: O(n * m * log(n * m)) time and O(n * m) space for an n x m grid.
from heapq import heappop, heappush
from math import inf
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
n, m = len(moveTime), len(moveTime[0])
dist = [[inf] * m for _ in range(n)]
dist[0][0] = 0
pq = [(0, 0, 0)]
dirs = (-1, 0, 1, 0, -1)
while 1:
d, i, j = heappop(pq)
if i == n - 1 and j == m - 1:
return d
if d > dist[i][j]:
continue
for a, b in zip(dirs, dirs[1:]):
x, y = i + a, j + b
if 0 <= x < n and 0 <= y < m:
t = max(moveTime[x][y], dist[i][j]) + 1
if dist[x][y] > t:
dist[x][y] = t
heappush(pq, (t, x, y))