8000 Create Find Minimum Time to Reach Last Room I.py · erjan/coding_exercises@1984233 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1984233

Browse files
authored
Create Find Minimum Time to Reach Last Room I.py
1 parent 592b8c9 commit 1984233

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
There is a dungeon with n x m rooms arranged as a grid.
2+
3+
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.
4+
5+
Return the minimum time to reach the room (n - 1, m - 1).
6+
7+
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
8+
9+
10+
------------------------------------------------------------------------------------------------
11+
class Solution:
12+
def minTimeToReach(self, moveTime: List[List[int]]) -> int:
13+
R, C = len(moveTime), len(moveTime[0])
14+
15+
def isOutside(i, j):
16+
return i < 0 or i >= R or j < 0 or j >= C
17+
18+
def idx(i, j):
19+
return i * C + j
20+
21+
N = R * C
22+
time = [2**31] * N
23+
pq = [0]
24+
25+
time[0] = 0
26+
while len(pq):
27+
tij = heappop(pq)
28+
t, ij = tij >> 32, tij & ((1 << 30) - 1)
29+
i, j = divmod(ij, C)
30+
if i == R - 1 and j == C - 1:
31+
return t
32+
33+
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
34+
r, s = i + di, j + dj
35+
if isOutside(r, s):
36+
continue
37+
38+
nextTime=max(t, moveTime[r][s])+1
39+
40+
rs = idx(r, s)
41+
if nextTime < time[rs]:
42+
time[rs] = nextTime
43+
heappush(pq, (nextTime << 32) + rs)
44+
return -1

0 commit comments

Comments
 (0)
0