-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind Minimum Time to Reach Last Room I.py
More file actions
44 lines (32 loc) · 1.51 KB
/
Find Minimum Time to Reach Last Room I.py
File metadata and controls
44 lines (32 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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 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.
------------------------------------------------------------------------------------------------
class Solution:
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
R, C = len(moveTime), len(moveTime[0])
def isOutside(i, j):
return i < 0 or i >= R or j < 0 or j >= C
def idx(i, j):
return i * C + j
N = R * C
time = [2**31] * N
pq = [0]
time[0] = 0
while len(pq):
tij = heappop(pq)
t, ij = tij >> 32, tij & ((1 << 30) - 1)
i, j = divmod(ij, C)
if i == R - 1 and j == C - 1:
return t
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
r, s = i + di, j + dj
if isOutside(r, s):
continue
nextTime=max(t, moveTime[r][s])+1
rs = idx(r, s)
if nextTime < time[rs]:
time[rs] = nextTime
heappush(pq, (nextTime << 32) + rs)
return -1