SDE & MLE Prep

1631. Path With Minimum Effort

Problem

Walk from the top-left to the bottom-right cell of heights, moving up, down, left or right. A route's effort is the largest absolute height difference between two consecutive cells on it. Return the minimum effort.

Example: [[1,2,2],[3,8,2],[5,3,5]] → 2

Constraints: up to 100 × 100.

Effort of a path = max |height difference| along it. Dijkstra with cost = max(cost, |Δh|).

Complexity: O(R·C log(R·C)).

class Solution:
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        R, C = len(heights), len(heights[0])
        best = [[float("inf")] * C for _ in range(R)]
        best[0][0] = 0
        pq = [(0, 0, 0)]
        while pq:
            e, r, c = heappop(pq)
            if (r, c) == (R - 1, C - 1):
                return e
            if e > best[r][c]:
                continue
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < R and 0 <= nc < C:
                    ne = max(e, abs(heights[nr][nc] - heights[r][c]))
                    if ne < best[nr][nc]:
                        best[nr][nc] = ne
                        heappush(pq, (ne, nr, nc))