|
| 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