Skip to content

Commit 8334af5

Browse files
authored
Create: 1631-path-with-minimum-effort.py
1 parent c7e91f1 commit 8334af5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def minimumEffortPath(self, heights: List[List[int]]) -> int:
3+
m, n = len(heights), len(heights[0])
4+
5+
efforts = [[float('inf')] * n for _ in range(m)]
6+
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
7+
8+
efforts[0][0] = 0
9+
pq = [(0, 0, 0)] # (effort, row, col)
10+
11+
while pq:
12+
curEffort, i, j = heapq.heappop(pq)
13+
14+
# reached the bottom-right corner => return the effort
15+
if i == m - 1 and j == n - 1:
16+
return curEffort
17+
18+
for dx, dy in directions:
19+
x, y = i + dx, j + dy
20+
21+
if 0 <= x < m and 0 <= y < n:
22+
newEffort = max(abs(heights[x][y] - heights[i][j]), curEffort)
23+
24+
if newEffort < efforts[x][y]:
25+
efforts[x][y] = newEffort
26+
heapq.heappush(pq, (newEffort, x, y))
27+
28+
return efforts[m - 1][n - 1]

0 commit comments

Comments
 (0)