The Mountain Hiker's Challenge

You're a hiker preparing for an epic mountain adventure! 🏔️ You have a detailed heights map represented as a 2D grid where heights[row][col] shows the elevation at each point.

Your mission: Travel from the top-left corner (0, 0) to the bottom-right corner (rows-1, columns-1) using the path that requires the minimum effort.

You can move up, down, left, or right to adjacent cells. The effort of any path is defined as the maximum absolute difference in heights between any two consecutive cells along that route.

Goal: Find the minimum effort required to complete your hike from start to finish.

Example: If you move from height 5 to height 8, then to height 3, your effort for this path would be max(|5-8|, |8-3|) = max(3, 5) = 5.

Input & Output

example_1.py — Basic Mountain Path
$ Input: heights = [[1,2,2],[3,8,2],[5,3,5]]
Output: 2
💡 Note: The path [1,3,5,3,5] has a maximum effort of 2. This is better than the path [1,2,2,2,5] which has maximum effort of 3.
example_2.py — Steep Terrain
$ Input: heights = [[1,2,3],[3,8,4],[5,3,5]]
Output: 1
💡 Note: The path [1,2,3,4,5] has maximum effort of 1, which is the minimum possible for this terrain.
example_3.py — Single Cell
$ Input: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
Output: 0
💡 Note: This path has no effort required since we can find a route where all consecutive cells have the same height.

Constraints

  • rows == heights.length
  • columns == heights[i].length
  • 1 ≤ rows, columns ≤ 100
  • 1 ≤ heights[i][j] ≤ 106

Visualization

Tap to expand
Path With Minimum Effort INPUT Heights Map (3x3 Grid) 1 START 2 2 3 8 2 5 3 5 END Input Array: [[1,2,2], [3,8,2], [5,3,5]] Move: Up, Down, Left, Right Effort = Max height diff in path ALGORITHM (BFS) 1 Initialize Queue: [(0,0)], effort=0 Distance array: all INF 2 BFS Exploration For each cell, check all 4 neighbors 3 Calculate Effort new_effort = max(curr, |height[curr]-height[next]|) 4 Update & Continue If new_effort < dist[next] update and add to queue Optimal Path Found: 1 2 2 2 5 Path FINAL RESULT Optimal Path Highlighted 1 2 2 3 8 2 5 3 5 Max Differences: |1-2|=1, |2-2|=0, |2-2|=0 |2-5|=3 (avoid!) Max effort on path = 2 Output: 2 Key Insight: BFS finds the minimum effort path by exploring cells level by level. We track the minimum effort to reach each cell and update only when a better path is found. The effort of a path is the MAXIMUM height difference between consecutive cells, not the sum of differences. TutorialsPoint - Path With Minimum Effort | BFS Approach
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
42.3K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen