Path With Minimum Effort (LeetCode 1631): Solution and Explanation
You are given a grid of heights and must walk from the top-left cell to the bottom-right cell, moving in four directions. A path's effort is the largest absolute height difference between any two consecutive cells on it. Return the smallest effort any path can achieve.
Watch it run step by step
Try your own input and write the code →Intuition
The cost of a path is not a sum, it is a maximum, so a plain BFS that counts steps does not help, and trying every path is exponential. But notice that the effort can only stay the same or grow as a path gets longer: extending a path to a new cell gives effort max(old effort, new step). That monotonic property is exactly what Dijkstra's algorithm needs.
So run Dijkstra with a modified relaxation. Keep dist[r][c], the smallest effort found so far to reach a cell, and a min-heap ordered by effort. When a cell is popped, its effort is final because any other route to it would have to pass through cells with effort at least as large. Moving to a neighbor costs max(effort, abs(height difference)), and if that beats the neighbor's recorded value, push it.
Since the heap always pops the smallest effort first, the first time the target cell comes off the heap its effort is the answer. Stale heap entries, those whose effort is larger than the cell's current best, are skipped when popped.
Approach: Dijkstra with max-edge path cost
- Fill
distwith infinity, setdist[0][0] = 0, and push(0, 0, 0)onto a min-heap of(effort, row, col). - Pop the smallest-effort entry. If it is the bottom-right cell, return its effort.
- If the popped effort is larger than
dist[r][c], the entry is stale, so skip it. - For each in-bounds neighbor, compute
new_effort = max(effort, abs(heights[nr][nc] - heights[r][c])). - If
new_effortis smaller thandist[nr][nc], update it and push the neighbor. - If the heap somehow empties, return
dist[m-1][n-1].
Step-by-step example
heights = [[1,2,2],[3,8,2],[5,3,5]]
- Start at (0,0) with effort 0. Neighbors (0,1) costs 1 and (1,0) costs 2; both are pushed.
- Pop (0,1) at 1. Neighbor (0,2) gets
max(1, 0) = 1and (1,1) getsmax(1, 6) = 6. Pop (0,2) at 1, which gives (1,2) effort 1. Pop (1,2) at 1, which gives (2,2) effortmax(1, 3) = 3. - Pop (1,0) at 2. It improves (1,1) to
max(2, 5) = 5and gives (2,0) effort 2. - Pop (2,0) at 2, giving (2,1) effort
max(2, 2) = 2. Pop (2,1) at 2, which improves (2,2) from 3 tomax(2, 2) = 2. - Pop (2,2) at effort 2. It is the target, so the answer is 2, via the path 1, 3, 5, 3, 5.
Code: Python, Java, C++
1class Solution:
2 def minimumEffortPath(self, heights: List[List[int]]) -> int:
3 m, n = len(heights), len(heights[0])
4 dist = [[float('inf')] * n for _ in range(m)]
5 dist[0][0] = 0
6 heap = [(0, 0, 0)] # (effort, row, col)
7 dirs = [(0, 1), (0, -1), (1, 0), (-1, 0)]
8
9 while heap:
10 effort, r, c = heapq.heappop(heap)
11 if r == m - 1 and c == n - 1:
12 return effort
13 if effort > dist[r][c]:
14 continue
15 for dr, dc in dirs:
16 nr, nc = r + dr, c + dc
17 if 0 <= nr < m and 0 <= nc < n:
18 new_effort = max(effort, abs(heights[nr][nc] - heights[r][c]))
19 if new_effort < dist[nr][nc]:
20 dist[nr][nc] = new_effort
21 heapq.heappush(heap, (new_effort, nr, nc))
22
23 return dist[m - 1][n - 1]1class Solution {
2 public int minimumEffortPath(int[][] heights) {
3 int m = heights.length, n = heights[0].length;
4 int[][] dist = new int[m][n];
5 for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
6 dist[0][0] = 0;
7 PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
8 heap.offer(new int[]{0, 0, 0});
9 int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
10
11 while (!heap.isEmpty()) {
12 int[] curr = heap.poll();
13 int effort = curr[0], r = curr[1], c = curr[2];
14 if (r == m - 1 && c == n - 1) return effort;
15 if (effort > dist[r][c]) continue;
16 for (int[] d : dirs) {
17 int nr = r + d[0], nc = c + d[1];
18 if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
19 int newEffort = Math.max(effort, Math.abs(heights[nr][nc] - heights[r][c]));
20 if (newEffort < dist[nr][nc]) {
21 dist[nr][nc] = newEffort;
22 heap.offer(new int[]{newEffort, nr, nc});
23 }
24 }
25 }
26 }
27
28 return dist[m - 1][n - 1];
29 }
30}1class Solution {
2public:
3 int minimumEffortPath(vector<vector<int>>& heights) {
4 int m = heights.size(), n = heights[0].size();
5 vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
6 dist[0][0] = 0;
7 priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<>> heap;
8 heap.push({0, 0, 0});
9 vector<pair<int, int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
10
11 while (!heap.empty()) {
12 auto [effort, r, c] = heap.top(); heap.pop();
13 if (r == m - 1 && c == n - 1) return effort;
14 if (effort > dist[r][c]) continue;
15 for (auto [dr, dc] : dirs) {
16 int nr = r + dr, nc = c + dc;
17 if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
18 int newEffort = max(effort, abs(heights[nr][nc] - heights[r][c]));
19 if (newEffort < dist[nr][nc]) {
20 dist[nr][nc] = newEffort;
21 heap.push({newEffort, nr, nc});
22 }
23 }
24 }
25 }
26
27 return dist[m - 1][n - 1];
28 }
29};Time and space complexity
O(m × n × log(m × n))
Each cell can be pushed a few times (once per improvement from one of its four neighbors), and every heap operation costs O(log(m × n)).
O(m × n)
The dist grid holds one value per cell and the heap holds at most a constant multiple of the cell count.
Other approaches
Binary search plus BFS (time O(m × n × log H), space O(m × n))
Binary search the answer between 0 and the largest height difference, and for each guess run a BFS that only uses steps no larger than the guess. Simple and effective when heights are bounded.
Union-find over sorted edges (time O(m × n × log(m × n)), space O(m × n))
Sort all edges between adjacent cells by height difference and union them in that order, stopping as soon as the start and end cells are connected. The weight of the last edge added is the answer.
Common mistakes
- Summing the differences like a normal shortest path. The effort is a maximum, so the relaxation must use
max(effort, diff), noteffort + diff. - Returning when the target is first pushed rather than first popped. A later route might still lower its effort before it reaches the top of the heap.
- Skipping the stale-entry check. Without
if effort > dist[r][c]: continue, outdated entries trigger needless relaxations and slow the search down. - Forgetting that a 1 by 1 grid has effort 0. The code handles this because the start cell is also the target and is popped immediately.
Frequently asked questions
Why does Dijkstra work when the cost is a maximum?
Dijkstra only needs path costs that never decrease as the path grows. Taking the max with a non-negative step satisfies that, so the first time a cell is popped its effort is optimal.
What is the time complexity of Path With Minimum Effort?
With Dijkstra and a binary heap it is O(m × n × log(m × n)), since each cell is relaxed a bounded number of times and each heap operation is logarithmic.
Can I solve it with binary search?
Yes. Binary search the effort limit and check reachability with BFS or DFS using only steps within the limit. It adds a factor of log of the height range instead of a log of the grid size.
Why not use plain BFS?
Plain BFS minimizes the number of steps, not the largest step. A longer path with gentle slopes can have lower effort than a short steep one.