The Gentlest Hike

Medium · Topological Sort & Shortest Paths · about 25 min

A hiking map is a grid heights with r rows and c columns. You start at the top-left cell and want to reach the bottom-right cell, moving up, down, left or right one cell at a time.

The steepness of a route is the largest absolute height difference between two cells next to each other on that route. Return the smallest possible steepness of a route from start to finish.

  • 1 <= r, c <= 100, 1 <= heights[i][j] <= 10^6. A 1 × 1 map has steepness 0.

Example: gentlest_hike([[1, 2, 2], [3, 8, 2], [5, 3, 5]]) → 2 (1 → 3 → 5 → 3 → 5 never changes by more than 2).

Hints

  • This is a shortest-path problem where the cost of a route is its worst step, not its total.
  • Dijkstra still works: when you move to a neighbour, its candidate cost is the larger of your cost and the step you just took.
  • Allow all four directions; the best route may go up or left.

Learn the pattern first: the Topological Sort & Shortest Paths lesson.

More Topological Sort & Shortest Paths problems