Path With Minimum Effort

Pattern: Shortest paths

medium

A path's effort is its largest height difference between neighbouring cells. Run Dijkstra where the cost of reaching a cell is the smallest possible 'largest step' so far; extending a path costs max(current, step). The first time the bottom-right cell is taken from the heap, its value is the answer.

The problem

Given a grid of heights, move up, down, left or right from the top-left to the bottom-right. A route's effort is the largest absolute height difference between two consecutive cells. Return the smallest possible effort.

Think first

  • How is a route's cost measured?
  • Does Dijkstra still work with 'max' instead of 'sum'?
  • What else could work?

Hints

    Brute force, and why it fails

    Try every route: exponential. Binary search plus BFS is O(R × C × log(max height)).

    The key insight

    Dijkstra only needs costs that never decrease along a path, and the largest step has that property.

    Dry run

    heights [[1, 2, 2], [3, 8, 2], [5, 3, 5]]. Start effort 0.

    Step 1 of 3

    The plan

    effort = inf; effort[start] = 0; heap
    pop (e, cell): for each neighbour: ne = max(e, |height diff|); if smaller: update, push
    

    Complexity

    Time
    O(R × C log(R × C))
    Space
    O(R × C)

    Dijkstra over the grid.

    Edge cases

    • A 1 × 1 grid: 0.
    • A flat grid: 0.
    • One big wall.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int minimumEffortPath(int[][] heights) {
            int R = heights.length, C = heights[0].length;
            int[][] effort = new int[R][C];         // the smallest "largest step" needed to reach each cell
            for (int[] row : effort) Arrays.fill(row, Integer.MAX_VALUE);
            effort[0][0] = 0;
            PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);   // {effort, r, c}
            pq.add(new int[]{0, 0, 0});
            int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
            while (!pq.isEmpty()) {                 // Dijkstra, where a path costs its largest step instead of its sum
                int[] cur = pq.poll();
                if (cur[1] == R - 1 && cur[2] == C - 1) return cur[0];
                if (cur[0] > effort[cur[1]][cur[2]]) continue;
                for (int[] d : dirs) {
                    int r = cur[1] + d[0], c = cur[2] + d[1];
                    if (r < 0 || c < 0 || r >= R || c >= C) continue;
                    int e = Math.max(cur[0], Math.abs(heights[r][c] - heights[cur[1]][cur[2]]));
                    if (e < effort[r][c]) { effort[r][c] = e; pq.add(new int[]{e, r, c}); }
                }
            }
            return 0;
        }
    }

    C++

    class Solution {
    public:
        int minimumEffortPath(vector<vector<int>>& heights) {
            int R = static_cast<int>(heights.size()), C = static_cast<int>(heights[0].size());
            vector<vector<int>> effort(R, vector<int>(C, INT_MAX));   // the smallest "largest step" to reach each cell
            effort[0][0] = 0;
            priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;   // {effort, r, c}
            pq.push(vector<int>{0, 0, 0});
            int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
            while (!pq.empty()) {                   // Dijkstra, where a path costs its largest step instead of its sum
                vector<int> cur = pq.top();
                pq.pop();
                if (cur[1] == R - 1 && cur[2] == C - 1) return cur[0];
                if (cur[0] > effort[cur[1]][cur[2]]) continue;
                for (int k = 0; k < 4; k++) {
                    int r = cur[1] + dr[k], c = cur[2] + dc[k];
                    if (r < 0 || c < 0 || r >= R || c >= C) continue;
                    int e = max(cur[0], abs(heights[r][c] - heights[cur[1]][cur[2]]));
                    if (e < effort[r][c]) { effort[r][c] = e; pq.push(vector<int>{e, r, c}); }
                }
            }
            return 0;
        }
    };

    Python

    import heapq
    
    class Solution:
        def minimumEffortPath(self, heights: list[list[int]]) -> int:
            R, C = len(heights), len(heights[0])
            effort = [[float("inf")] * C for _ in range(R)]   # the smallest "largest step" to reach each cell
            effort[0][0] = 0
            pq = [(0, 0, 0)]
            while pq:                               # Dijkstra, where a path costs its largest step instead of its sum
                e, r, c = heapq.heappop(pq)
                if (r, c) == (R - 1, C - 1):
                    return e
                if e > effort[r][c]:
                    continue
                for x, y in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                    if 0 <= x < R and 0 <= y < C:
                        ne = max(e, abs(heights[x][y] - heights[r][c]))
                        if ne < effort[x][y]:
                            effort[x][y] = ne
                            heapq.heappush(pq, (ne, x, y))
            return 0

    Common mistakes

    • Adding steps instead of taking the maximum.
    • Returning when a cell is pushed rather than popped.

    Similar problems