Path With Minimum Effort
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #1631
You walk from the top-left to the bottom-right of a heights grid, moving in 4 directions. A route's effort is the largest absolute height difference between two consecutive cells on it. Return the minimum effort.
Examples
[[1,2,2],[3,8,2],[5,3,5]] → 2 (1→3→5→3→5)
[[1,2,3],[3,8,4],[5,3,5]] → 1
[[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]] → 0Hints
- Cost is the max edge along the path, not the sum. Does Dijkstra still work?
- Yes. The max of non-negative values never decreases as a path grows, which is all Dijkstra needs.
- An alternative: binary-search the answer E and BFS using only edges ≤ E.
Approach
Minimax Dijkstra: eff[cell] = best known effort to reach the cell. Pop the smallest, and for each neighbor cand = max(eff, |h1 − h2|). If that beats the neighbor's current value, push it. The first time the target is popped, its effort is final.
Why does this work? Dijkstra needs the path cost to be monotone non-decreasing when you extend a path, and max satisfies that. Alternatives: binary search over effort with BFS (O(mn log H)), or Kruskal-style union-find adding edges in increasing weight until the corners connect.
Complexity
Time: O(mn log(mn)) with Dijkstra (O(mn log H) with binary search). Space: O(mn).
Python solution
import heapq
def minimumEffortPath(heights):
R, C = len(heights), len(heights[0])
best = [[float('inf')] * C for _ in range(R)]
best[0][0] = 0
heap = [(0, 0, 0)]
while heap:
e, r, c = heapq.heappop(heap)
if (r, c) == (R - 1, C - 1):
return e
if e > best[r][c]:
continue
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C:
ne = max(e, abs(heights[nr][nc] - heights[r][c]))
if ne < best[nr][nc]:
best[nr][nc] = ne
heapq.heappush(heap, (ne, nr, nc))
return 0JavaScript solution
function minimumEffortPath(heights) {
// Binary search on the answer + BFS reachability using only edges ≤ limit.
const R = heights.length, C = heights[0].length;
const ok = (limit) => {
const seen = Array.from({ length: R }, () => new Array(C).fill(false));
const q = [[0, 0]]; seen[0][0] = true;
for (let h = 0; h < q.length; h++) {
const [r, c] = q[h];
if (r === R - 1 && c === C - 1) return true;
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
if (nr < 0 || nc < 0 || nr >= R || nc >= C || seen[nr][nc]) continue;
if (Math.abs(heights[nr][nc] - heights[r][c]) > limit) continue;
seen[nr][nc] = true; q.push([nr, nc]);
}
}
return false;
};
let lo = 0, hi = 1e6;
while (lo < hi) { const mid = (lo + hi) >> 1; if (ok(mid)) hi = mid; else lo = mid + 1; }
return lo;
}