Find Minimum Time to Reach Last Room II Problem
Description
LeetCode Problem 3342.
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 when you can start moving to that room. You start from the room (0, 0) at time t = 0 and can move to an adjacent room. Moving between adjacent rooms takes one second for one move and two seconds for the next, alternating between the two.
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: 7
Explanation:
The minimum time required is 7 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 two seconds.
Example 2:
Input: moveTime = [[0,0,0,0],[0,0,0,0]]
Output: 6
Explanation:
The minimum time required is 6 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 two seconds.
- At time t == 3, move from room (1, 1) to room (1, 2) in one second.
- At time t == 4, move from room (1, 2) to room (1, 3) in two seconds.
Example 3:
Input: moveTime = [[0,1],[1,2]]
Output: 4
Constraints:
2 <= n == moveTime.length <= 7502 <= m == moveTime[i].length <= 7500 <= 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. The moves alternate between taking one and two seconds, and the first move takes one second, so the move out of room (i, j) takes 1 if (i + j) is even and 2 if it is odd. This only depends on the cell, so it fits in the edge weight.
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 + (i + j) % 2; 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]) + (i + j) % 2 + 1
if dist[x][y] > t:
dist[x][y] = t
heappush(pq, (t, x, y))