Path With Minimum Effort

35 min · minimumEffortPath()

A hiking route is judged by its roughest step, not by the sum of all its climbs.

You receive a rectangular grid heights. Start at the top-left cell and reach the bottom-right cell by moving up, down, left, or right. The effort of a path is the largest absolute height difference across any single move on that path.

Return the smallest effort achievable by any valid path. A one-cell hike takes no moves, so its effort is 0.

Constraints

  • 1 <= heights.length <= 100
  • 1 <= heights[i].length <= 100
  • Every row has the same length.
  • 1 <= heights[row][col] <= 1_000_000

Hints

Change what distance means

Reaching a cell with effort e means the roughest step so far is e. Crossing an edge of size d changes that route's effort to max(e, d), not e + d.

Dijkstra still fits

Keep the smallest known effort for each cell in a min-heap. Pop the route with the lowest current effort and relax its four neighbors using that max rule.

Another lens: can you cross?

For a guessed effort limit, BFS can test whether the destination is reachable using only steps at or below that limit. Reachability is monotonic, so binary search works.

Follow-up

How would the result change if diagonal moves were allowed too? Which part of your algorithm would need to change?

Visible cases

Examples

Example 1

ready
Input
heights = [
  [
    1,
    2,
    2
  ],
  [
    3,
    8,
    2
  ],
  [
    5,
    3,
    5
  ]
]
Expected
2
Why
a route along the left and bottom keeps every step at 2 or less

Example 2

ready
Input
heights = [
  [
    1,
    2,
    3
  ],
  [
    3,
    8,
    4
  ],
  [
    5,
    3,
    5
  ]
]
Expected
1
Why
the outer route changes height by at most 1 per move

Example 3

ready
Input
heights = [
  [
    7
  ]
]
Expected
0
Why
one cell needs no movement

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite