Path With Minimum Effort

Medium Graphs Dijkstra

Path With Minimum Effort is a medium graphs problem solved with the dijkstra pattern. The best approach, optimal (dijkstra on the biggest step), runs in O(rows · cols · log(rows · cols)) time and O(rows · cols) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from binary search on the effort + bfs up.

Problem

You are planning a hike across a map given as a rows × cols grid heights, where heights[r][c] is the height of the cell in row r and column c. You start in the top left cell (0, 0) and want to reach the bottom right cell (rows - 1, cols - 1). From any cell you may move up, down, left or right to a neighbouring cell.

The effort of a route is the largest absolute height difference between two cells that follow each other on that route.

Return the minimum effort needed to go from the top left cell to the bottom right cell.

Examples

Example 1

Input
heights = [[4, 6, 9], [2, 9, 5], [3, 4, 6]]
Output
2
Why
Go down to 2, down to 3, right to 4, right to 6. The steps change the height by 2, 1, 1 and 2, so the biggest step is 2. No route can do better, because both first moves out of the start change the height by 2.

Example 2

Input
heights = [[1, 10, 6, 7, 9, 10, 4, 9]]
Output
9
Why
With one row there is only one route, and it has to climb from 1 to 10 at the start.

Example 3

Input
heights = [[7]]
Output
0
Why
You already stand on the target cell, so there are no steps at all.

Constraints

  • rows == heights.length, cols == heights[i].length
  • 1 <= rows, cols <= 100
  • 1 <= heights[i][j] <= 10^6

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Binary search on the effort + BFSO(rows · cols · log H)O(rows · cols)
Union-Find on sorted edgesO(rows · cols · log(rows · cols))O(rows · cols)
Optimal (Dijkstra on the biggest step)O(rows · cols · log(rows · cols))O(rows · cols)

1Binary search on the effort + BFS

TimeO(rows · cols · log H)Each BFS visits every cell at most once, and there are about log of 10^6, around 20, guesses.
SpaceO(rows · cols)The seen grid and the BFS queue hold up to rows · cols cells.

Guess a limit and ask a yes-or-no question: can we walk from the top left to the bottom right using only steps whose height change is at most the limit? A BFS answers it. If a limit works, every bigger limit works too, so the answers look like no, no, ..., yes, yes. Binary search finds the first yes.

  1. Search the limit between 0 and 10^6.
  2. For a guess mid, run a BFS from (0, 0) that only takes steps with a height change of at most mid.
  3. If the BFS reaches the bottom right cell, mid is enough: keep it and search lower. Otherwise search higher.
  4. When the range closes, it holds the smallest limit that works.
class Solution {
    private static final int[] DR = { 1, -1, 0, 0 };
    private static final int[] DC = { 0, 0, 1, -1 };

    public int minimumEffortPath(int[][] heights) {
        int lo = 0, hi = 1_000_000;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (canReach(heights, mid)) hi = mid;
            else lo = mid + 1;
        }
        return lo;
    }

    // BFS that only takes steps with a height change of at most limit
    private boolean canReach(int[][] h, int limit) {
        int rows = h.length, cols = h[0].length;
        boolean[][] seen = new boolean[rows][cols];
        ArrayDeque<int[]> queue = new ArrayDeque<>();
        queue.add(new int[] { 0, 0 });
        seen[0][0] = true;
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int r = cell[0], c = cell[1];
            if (r == rows - 1 && c == cols - 1) return true;
            for (int d = 0; d < 4; d++) {
                int nr = r + DR[d], nc = c + DC[d];
                if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || seen[nr][nc]) continue;
                if (Math.abs(h[nr][nc] - h[r][c]) > limit) continue;
                seen[nr][nc] = true;
                queue.add(new int[] { nr, nc });
            }
        }
        return false;
    }
}

2Union-Find on sorted edges

TimeO(rows · cols · log(rows · cols))There are about 2 · rows · cols edges; sorting them dominates. Each union and find is nearly constant with path halving.
SpaceO(rows · cols)The edge list and the parent array both grow with the number of cells.

Think of every pair of side-by-side cells as an edge whose weight is their height difference. Add the edges from the cheapest up, joining cells into groups with Union-Find. The moment the top left and the bottom right fall into the same group, a route exists whose biggest step is the edge just added, and no cheaper set of edges could connect them.

  1. Number cell (r, c) as r · cols + c and list every right and down edge with its weight.
  2. Sort the edges by weight.
  3. Union the two ends of each edge in order. After each union, check if cell 0 and cell rows · cols - 1 share a root.
  4. The weight of the edge that first joins them is the answer. A single cell needs no edge: answer 0.
class Solution {
    private int[] parent;

    public int minimumEffortPath(int[][] heights) {
        int rows = heights.length, cols = heights[0].length;
        int n = rows * cols;
        if (n == 1) return 0;
        List<int[]> edges = new ArrayList<>();
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                int id = r * cols + c;
                if (c + 1 < cols) edges.add(new int[] { Math.abs(heights[r][c] - heights[r][c + 1]), id, id + 1 });
                if (r + 1 < rows) edges.add(new int[] { Math.abs(heights[r][c] - heights[r + 1][c]), id, id + cols });
            }
        }
        edges.sort((a, b) -> Integer.compare(a[0], b[0]));
        parent = new int[n];
        for (int i = 0; i < n; i++) parent[i] = i;
        for (int[] e : edges) {
            parent[find(e[1])] = find(e[2]);
            if (find(0) == find(n - 1)) return e[0];
        }
        return 0;
    }

    private int find(int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
}

3Optimal (Dijkstra on the biggest step)

TimeO(rows · cols · log(rows · cols))Each cell can be pushed a few times (once per improvement from a neighbour), and every heap operation costs a log.
SpaceO(rows · cols)The effort grid and the heap both hold up to a constant times rows · cols entries.

Run Dijkstra, but let the cost of a route be its biggest step instead of its total. Reaching a neighbour costs max(effort so far, this step), which never goes down as a route grows, so the greedy rule of Dijkstra still holds: the cell with the smallest effort in the heap is final. Stop as soon as the bottom right cell leaves the heap.

  1. effort[r][c] = best known effort to reach (r, c); start with 0 at (0, 0) and infinity elsewhere.
  2. Pop the entry with the smallest effort. Skip it if a better effort was already found for that cell.
  3. If it is the bottom right cell, return its effort.
  4. For each of the four neighbours, next = max(effort, |height difference|). If next beats the neighbour's best, store it and push it.
class Solution {
    public int minimumEffortPath(int[][] heights) {
        int rows = heights.length, cols = heights[0].length;
        int[][] effort = new int[rows][cols];
        for (int[] row : effort) Arrays.fill(row, Integer.MAX_VALUE);
        effort[0][0] = 0;
        int[] dr = { 1, -1, 0, 0 }, dc = { 0, 0, 1, -1 };
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
        pq.add(new int[] { 0, 0, 0 });
        while (!pq.isEmpty()) {
            int[] cur = pq.poll();
            int e = cur[0], r = cur[1], c = cur[2];
            if (e > effort[r][c]) continue;
            if (r == rows - 1 && c == cols - 1) return e;
            for (int d = 0; d < 4; d++) {
                int nr = r + dr[d], nc = c + dc[d];
                if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
                int next = Math.max(e, Math.abs(heights[nr][nc] - heights[r][c]));
                if (next < effort[nr][nc]) {
                    effort[nr][nc] = next;
                    pq.add(new int[] { next, nr, nc });
                }
            }
        }
        return 0;
    }
}

Edge cases to test

  • A single cell (answer 0)
  • A single row or a single column: only one route, so the answer is its biggest step
  • All cells the same height (answer 0)
  • The best route goes up, left or back, not only down and right
  • The shortest route is not the easiest one

Hints

Hint 1

The effort of a route is its single biggest step, not the sum of its steps.

Hint 2

If you can reach the corner using only steps of at most e, you can also do it with any limit bigger than e. So you can binary search the answer and check each guess with a BFS.

Hint 3

Dijkstra still works if you replace 'distance plus weight' with 'the larger of the effort so far and this step'. The first time the corner leaves the heap, its effort is the answer.

FAQ

What is the best time complexity for Path With Minimum Effort?

Optimal (Dijkstra on the biggest step) runs in O(rows · cols · log(rows · cols)) time and O(rows · cols) extra space. Each cell can be pushed a few times (once per improvement from a neighbour), and every heap operation costs a log.

Which pattern does Path With Minimum Effort use?

It is a graphs problem that uses the dijkstra pattern. Other problems with the same pattern: Network Delay Time, Find the City With the Smallest Number of Neighbors at a Threshold Distance, Cheapest Flights Within K Stops.

Is there a brute force solution for Path With Minimum Effort?

Yes. Binary search on the effort + BFS takes O(rows · cols · log H) time and O(rows · cols) space. Guess a limit and ask a yes-or-no question: can we walk from the top left to the bottom right using only steps whose height change is at most the limit?

Which edge cases should I test for Path With Minimum Effort?

A single cell (answer 0); A single row or a single column: only one route, so the answer is its biggest step; All cells the same height (answer 0); The best route goes up, left or back, not only down and right; The shortest route is not the easiest one.