Skip to content

Path With Minimum Effort

Cross a height map by the route whose single biggest climb or drop is as small as possible.

MediumShortest Paths
Solve on LeetCode

The problem

You get a rows x cols grid heights. You start at the top-left cell and want to reach the bottom-right cell, moving up, down, left or right. The effort of a route is the largest absolute height difference between two neighboring cells on it. Return the smallest effort of any route.

Input heights = [[1, 10, 6], [3, 8, 3], [5, 6, 4]]

Output 2

Down the left side and along the bottom, 1, 3, 5, 6, 4, the biggest step is 2. No route does better, since the first step from 1 goes to 3 or to 10.

Input heights = [[4, 7, 5]]

Output 3

There is only one route. Its steps are 3 and 2, and the effort is the bigger one, not their sum.

Key constraint: The cost of a route is its worst step, a maximum, not a sum of steps.

How to spot the pattern

  • You want the best route between two cells, but a route costs its single worst step.
  • Moves go in all 4 directions, so the best route may turn back, and a row-by-row DP can't follow it.
  • Steps have different costs, so plain BFS is not enough.

The idea

This is Dijkstra with one change: a route's cost is its largest step, so extending a route of effort e by a step of size s gives effort max(e, s). That cost never goes down as a route grows, which is all Dijkstra needs. So keep a min-heap of cells ordered by effort, always expand the cheapest one, and the first time you pop the bottom-right cell, its effort is the answer.

Brute force: Try every route with DFS and track the largest step on each, which takes exponential time.

Step by step

  1. 1Set effort to infinity for every cell except the start, which gets 0, and push (0, 0, 0) (effort, row, column) onto a min-heap.
  2. 2Pop the entry with the smallest effort; if it is the bottom-right cell, return that effort.
  3. 3Skip the entry if its effort is larger than the one stored for its cell, because a better route was already found.
  4. 4For each of the 4 neighbors, compute max(effort, abs(height difference)), and if that beats the neighbor's stored effort, store it and push the neighbor.

See the pattern move

The shortest paths pattern on a small example. Step through it, or press play.

Code

import heapq


class Solution:
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        rows, cols = len(heights), len(heights[0])
        # effort[r][c] = smallest effort of any route found so far to (r, c)
        effort = [[float("inf")] * cols for _ in range(rows)]
        effort[0][0] = 0
        heap = [(0, 0, 0)]  # (effort, row, col), smallest effort first
        while heap:
            e, r, c = heapq.heappop(heap)
            if r == rows - 1 and c == cols - 1:
                return e
            if e > effort[r][c]:
                continue  # an old entry; this cell was reached with less effort
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols:
                    # a route's effort is its biggest step, so combine with max, not +
                    new_effort = max(e, abs(heights[nr][nc] - heights[r][c]))
                    if new_effort < effort[nr][nc]:
                        effort[nr][nc] = new_effort
                        heapq.heappush(heap, (new_effort, nr, nc))
        return 0

Complexity

Time

O(R * C * log(R * C))

Space

O(R * C)

A cell is pushed at most once per neighbor, so the heap sees O(R * C) entries, and each push or pop costs O(log(R * C)).

Watch out for

  • Adding step sizes like a normal shortest path: combine with max, not +.
  • Marking a cell as done when you first push it: a later route can still reach it with less effort, so trust a cell only when it comes off the heap.
  • Moving only right and down: the best route may need to go up or left around a steep area.

Follow-up questions

Is there another way to solve it?

Binary search on the effort. For a guess x, a BFS that only takes steps of at most x tells you if you can cross; the smallest x that works is the answer, in O(R * C * log(max height)) time.

How would union-find solve it?

Sort all neighbor pairs by height difference and join them in that order. The difference at which the start and end cells first land in the same group is the answer.

In Hinglish

Yahan raaste ka cost sum nahi, uska sabse bada step hai. Dijkstra wahi rakho, bas `d + w` ki jagah `max(d, step)` lagao.

Related problems