-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1631_path_with_minimum_effort.py
More file actions
36 lines (30 loc) · 1.16 KB
/
Copy path1631_path_with_minimum_effort.py
File metadata and controls
36 lines (30 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
def valid(row, col):
return 0 <= row < m and 0 <= col < n
def check(effort):
directions = [(0,1),(1,0),(0,-1),(-1,0)]
seen = {(0,0)}
stack = [(0,0)]
while stack:
row, col = stack.pop()
if (row, col) == (m - 1, n - 1):
return True
for dx, dy in directions:
next_row, next_col = row + dy, col + dx
if valid(next_row, next_col) and (next_row, next_col) not in seen:
if abs(heights[next_row][next_col] - heights[row][col]) <= effort:
seen.add((next_row, next_col))
stack.append((next_row, next_col))
return False
left = 0
right = max(max(row) for row in heights)
m = len(heights)
n = len(heights[0])
while left <= right:
mid = (left + right) // 2
if check(mid):
right = mid - 1
else:
left = mid + 1
return left