Skip to content

Commit bf7c8b0

Browse files
authored
Create find-minimum-time-to-reach-last-room-ii.py
1 parent 9ecf1b2 commit bf7c8b0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Time: O(n * m * logn(n * m))
2+
# Space: O(n * m)
3+
4+
import heapq
5+
6+
7+
# dijkstra's algorithm
8+
class Solution(object):
9+
def minTimeToReach(self, moveTime):
10+
"""
11+
:type moveTime: List[List[int]]
12+
:rtype: int
13+
"""
14+
def dijkstra(start, target):
15+
DIRECTIONS = [(1, 0), (0, 1), (-1, 0), (0, -1)]
16+
dist = [[float("inf")]*len(moveTime[0]) for _ in xrange(len(moveTime))]
17+
dist[start[0]][start[1]] = 0
18+
min_heap = [(dist[start[0]][start[1]], start[0], start[1])]
19+
while min_heap:
20+
curr, i, j = heapq.heappop(min_heap)
21+
if curr != dist[i][j]:
22+
continue
23+
if (i, j) == target:
24+
break
25+
for di, dj in DIRECTIONS:
26+
ni, nj = i+di, j+dj
27+
c = (i+j)%2+1
28+
if not (0 <= ni < len(moveTime) and 0 <= nj < len(moveTime[0]) and dist[ni][nj] > max(moveTime[ni][nj], curr)+c):
29+
continue
30+
dist[ni][nj] = max(moveTime[ni][nj], curr)+c
31+
heapq.heappush(min_heap, (dist[ni][nj], ni, nj))
32+
return dist[target[0]][target[1]]
33+
34+
return dijkstra((0, 0), (len(moveTime)-1, len(moveTime[0])-1))

0 commit comments

Comments
 (0)