1631. Path With Minimum Effort
https://leetcode.com/problems/path-with-minimum-effort/


Last updated
https://leetcode.com/problems/path-with-minimum-effort/


Last updated
Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
Explanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
Explanation: This route does not require any effort.class Solution:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
M, N = len(heights), len(heights[0])
dirs = [(-1, 0), (1, 0), (0, 1), (0, -1)]
def bfs(limit):
visited, q = {(0, 0)}, deque([(0, 0)])
while q:
r, c = q.popleft()
if (r, c) == (len(heights) - 1, len(heights[0]) - 1): return True
for (dx, dy) in dirs:
x, y = r + dx, c + dy
if len(heights) > x >= 0 <= y < len(heights[0]) and abs(heights[r][c] - heights[x][y]) <= limit and (x, y) not in visited:
q.append((x, y))
visited.add((x, y))
return False
s, e = 0, 10 ** 6
while s < e:
m = s + e >> 1
if not bfs(m):
s = m + 1
else:
e = m
return s