Path With Minimum Effort
Medium
Topics
You are given a grid heights of size rows x columns. You start at the top-left cell and want to reach the bottom-right cell, moving up, down, left, or right.
The effort of a route is the maximum absolute height difference between two consecutive cells along it.
Return the minimum effort required to travel from the top-left to the bottom-right cell.
Example 1
Input: heights = [[1,2,2],[3,8,2],[5,3,5]] Output: 2 Explanation: The route 1 -> 2 -> 2 -> 2 -> 5 has a maximum difference of 2, better than going through 8.
Example 2
Input: heights = [[1,2,3],[3,8,4],[5,3,5]] Output: 1
Constraints
- rows == heights.length
- columns == heights[i].length
- 1 <= rows, columns <= 100
- 1 <= heights[i][j] <= 10^6
Editorial — intuition, approach, complexity and pitfalls
Intuition
The cost of a path is a maximum over its edges, not a sum, so plain Dijkstra's relaxation does not apply unchanged — but it almost does. Replace "distance so far plus edge weight" with "max(distance so far, edge weight)" and the greedy argument still holds, because that combining function is monotone. Pop the cell with the smallest bottleneck first and you have a minimax shortest path.
Approach
- Keep a grid
effortof best-known bottleneck values, all infinity except the start at 0. - Use a min-heap keyed by bottleneck value. Pop the smallest, and if it is the destination you are done — the first time you pop it, its value is optimal.
- For each neighbour, the candidate cost is
max(effort[cur], abs(height[next] - height[cur])). Push and record it if that beats the stored value. - Two alternatives interview well: binary search the answer and BFS to test feasibility at each threshold, or sort all edges ascending and union cells until the corners connect (Kruskal).
import heapq
class Solution:
def minimumEffortPath(self, heights):
m, n = len(heights), len(heights[0])
effort = [[float("inf")] * n for _ in range(m)]
effort[0][0] = 0
pq = [(0, 0, 0)]
while pq:
cost, r, c = heapq.heappop(pq)
if r == m - 1 and c == n - 1:
return cost
if cost > effort[r][c]:
continue
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
nxt = max(cost, abs(heights[nr][nc] - heights[r][c]))
if nxt < effort[nr][nc]:
effort[nr][nc] = nxt
heapq.heappush(pq, (nxt, nr, nc))
return 0Dry Run
grid 1 2 2
3 8 2
5 3 5
The cost of a path is the LARGEST single step on it, so the relaxation combines
with max rather than plus. Dijkstra still works, because a max is monotone.
pop (0, 0,0) improves (1,0) to 2 and (0,1) to 1
pop (1, 0,1) improves (1,1) to 6 and (0,2) to 1
pop (1, 0,2) improves (1,2) to 1
pop (1, 1,2) improves (2,2) to 3
pop (2, 1,0) improves (2,0) to 2 and (1,1) 6->5
pop (2, 2,0) improves (2,1) to 2
pop (2, 2,1) improves (2,2) 3->2
pop (2, 2,2) this is the destination
answer 2
Note (2,2) is improved twice, from 3 down to 2, by a route arriving from the left
rather than from above. Movement is four-directional and may go UP or LEFT, so
this is not a DP over a monotone grid and a row-major single pass would miss that
second route entirely.
The pop at (1,1) is worth following too. It is first set to 6 via (0,1) and later
to 5 via (1,0); the stale (6, 1, 1) entry stays on the heap and is discarded by
`if cost > effort[r][c]: continue` when it surfaces. Without that guard nothing is
wrong with the answer, but the heap keeps growing and large grids slow sharply.
Adding the differences instead of maxing them solves a different problem: this
grid then returns 4. And a 1x1 grid needs no moves at all, which the early
destination return handles by giving 0 before any neighbour is examined.Complexity
- Time — O(m x n log(m x n)) — Dijkstra over a grid graph with 4 edges per cell.
- Space — O(m x n) for the effort grid and the heap.
Common Pitfalls
- Adding edge weights instead of taking their maximum solves a different problem entirely. The combining step is
max. - A 1x1 grid needs no moves, so the answer is 0. Make sure the start-equals-destination case returns before entering the loop body.
- Skip stale heap entries with the
cost > effort[r][c]guard, or the heap grows and the run slows sharply on large grids. - Movement is four-directional and may go up or left — this is not a DP over a monotone grid, so a row-major single pass gives wrong answers.
Full Solution — all languages
class Solution:
def minimumEffortPath(self, grid):
import heapq
rows, cols = len(grid), len(grid[0])
effort = [[float('inf')] * cols for _ in range(rows)]
effort[0][0] = 0
heap = [(0, 0, 0)]
while heap:
cost, r, c = heapq.heappop(heap)
if r == rows - 1 and c == cols - 1:
return cost
if cost > effort[r][c]:
continue
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
step = max(cost, abs(grid[nr][nc] - grid[r][c]))
if step < effort[nr][nc]:
effort[nr][nc] = step
heapq.heappush(heap, (step, nr, nc))
return 0import java.util.*;
class Solution {
public int minimumEffortPath(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
int[][] effort = new int[rows][cols];
for (int[] row : effort) Arrays.fill(row, Integer.MAX_VALUE);
effort[0][0] = 0;
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
heap.add(new int[]{0, 0, 0});
int[][] D = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
while (!heap.isEmpty()) {
int[] cur = heap.poll();
int cost = cur[0], r = cur[1], c = cur[2];
if (r == rows - 1 && c == cols - 1) return cost;
if (cost > effort[r][c]) continue;
for (int[] d : D) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
int step = Math.max(cost, Math.abs(grid[nr][nc] - grid[r][c]));
if (step < effort[nr][nc]) {
effort[nr][nc] = step;
heap.add(new int[]{step, nr, nc});
}
}
}
return 0;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minimumEffortPath(vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size();
vector<vector<int>> effort(rows, vector<int>(cols, INT_MAX));
effort[0][0] = 0;
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> heap;
heap.push({0, 0, 0});
int D[4][2] = { {
1, 0
},
{
-1, 0
},
{
0, 1
},
{
0, -1
}
};
while (!heap.empty()) {
array<int, 3> cur = heap.top();
heap.pop();
int cost = cur[0], r = cur[1], c = cur[2];
if (r == rows - 1 && c == cols - 1) return cost;
if (cost > effort[r][c]) continue;
for (auto& d : D) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
int step = max(cost, abs(grid[nr][nc] - grid[r][c]));
if (step < effort[nr][nc]) {
effort[nr][nc] = step;
heap.push({step, nr, nc});
}
}
}
return 0;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var minimumEffortPath = function(grid) {
const rows = grid.length, cols = grid[0].length;
const effort = Array.from({ length: rows }, () => new Array(cols).fill(Infinity));
effort[0][0] = 0;
// Small grids here, so a scan for the cheapest frontier cell is enough;
// a binary heap is what keeps this near-linear at scale.
const seen = Array.from({ length: rows }, () => new Array(cols).fill(false));
for (;;) {
let br = -1, bc = -1, best = Infinity;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (!seen[r][c] && effort[r][c] < best) {
best = effort[r][c];
br = r;
bc = c;
}
}
}
if (br < 0) return 0;
if (br === rows - 1 && bc === cols - 1) return best;
seen[br][bc] = true;
for (const d of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const nr = br + d[0], nc = bc + d[1];
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
const step = Math.max(best, Math.abs(grid[nr][nc] - grid[br][bc]));
if (step < effort[nr][nc]) effort[nr][nc] = step;
}
}
};