Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 411b7d4

Browse files
authored
Create Find Minimum Time to Reach Last Room II.py
1 parent 1984233 commit 411b7d4

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
There is a dungeon with n x m rooms arranged as a grid.
3+
4+
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.
5+
6+
Return the minimum time to reach the room (n - 1, m - 1).
7+
8+
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
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, 0, 1)] # (time, ij, adjust)
24+
25+
time[0] = 0
26+
while len(pq):
27+
t, ij, adj = heappop(pq)
28+
i, j = divmod(ij, C)
29+
if i == R - 1 and j == C - 1:
30+
return t
31+
32+
for di, dj in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
33+
r, s = i + di, j + dj
34+
if isOutside(r, s):
35+
continue
36+
37+
nextTime=max(t, moveTime[r][s])+1+(1-adj)
38+
39+
rs = idx(r, s)
40+
if nextTime < time[rs]:
41+
time[rs] = nextTime
42+
heappush(pq, (nextTime, rs, 1-adj))
43+
return -1

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /