Python coding

Route with the smallest worst step

A hiker crosses a height map heights (a grid of integers) from the top-left cell to the bottom-right cell, moving one cell up, down, left or right at a time. The size of a step is the absolute difference between the two heights, and a route is only as hard as its worst (biggest) step. Return the smallest possible worst step over all routes.

The grid has 1 to 20 rows and columns, and heights may be negative. A single cell needs no steps: return 0.

Besides the tests, one large input (a 5×6 grid) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • smallest_worst_step([[1,3,5],[2,8,4],[3,4,5]]) → 1
  • smallest_worst_step([[0,0,0],[2,100,0],[1,3,5]]) → 2
  • smallest_worst_step([[1,1,1],[9,9,1],[1,1,1],[1,9,9],[1,1,1]]) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

It is a shortest-path problem with a twist: a route costs its biggest step, not the sum of its steps. Cells are nodes, and neighbors share an edge weighted by their height difference.

Hint 2

Run Dijkstra with a min-heap, but relax with max(worst_so_far, step) instead of a sum. Popping the smallest is still safe: extending a route never lowers its worst step.

Hint 3

The best route may go up or left around a cliff, so a right/down table is not enough. Minimizing the sum fails too: it prefers one jump of 5 to several steps of 2.

Solution and why it works
pythonO(R·C·log(R·C)), R×C grid · O(R·C)
import heapq


def smallest_worst_step(heights: list[list[int]]) -> int:
    rows, cols = len(heights), len(heights[0])
    worst = {(0, 0): 0}                  # smallest worst step known to reach each cell
    heap = [(0, 0, 0)]                   # (worst step so far, row, col)
    while heap:
        w, r, c = heapq.heappop(heap)
        if w > worst[(r, c)]:
            continue                     # stale entry: heapq has no decrease-key
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols:
                nw = max(w, abs(heights[nr][nc] - heights[r][c]))
                if nw < worst.get((nr, nc), float("inf")):
                    worst[(nr, nc)] = nw     # relax with max instead of +
                    heapq.heappush(heap, (nw, nr, nc))
    return worst[(rows - 1, cols - 1)]

A route costs the max of its steps, and extending a route never lowers that max, so Dijkstra's argument still holds: the cell popped with the smallest worst step is final. Only the relaxation changes, max(w, step) instead of w + step. Traps: a right/down table misses routes that go up or left around a cliff; minimizing the sum of steps prefers one jump of 5 to several steps of 2; BFS counts cells, not heights.