Algo-Sim › Grid Graphs
Path With Minimum Effort
Medium · Grid Graphs · step through it in Java, Python and C++ on your own input
A route costs its largest height difference, so run Dijkstra where extending a path takes the max, not the sum (bottleneck shortest path).
Problem
A grid holds heights. Walking up, down, left or right from cell to cell, a route’s effort is the largest absolute height difference between two consecutive cells on it. Return the least effort needed to go from the top-left cell to the bottom-right cell.
Constraints
- 1 ≤ rows, cols ≤ 100
- 1 ≤ heights[i][j] ≤ 10⁶
Edge cases to test
- One cell:
0 - All heights equal
- A route that detours around one big step
Follow-up questions
- What other method works?
- Binary search on the effort and check reachability with BFS (O(mn log H)), or add edges in increasing order with union-find until start and end connect.
- Why is Dijkstra still correct with max instead of sum?
- Extending a path never lowers its maximum, so the first time a cell is popped its cost is final.
Solution
Java
public int minimumEffortPath(int[][] heights) {
int rows = heights.length, cols = heights[0].length;
int[][] effort = new int[rows][cols];
for (int[] row : effort) Arrays.fill(row, Integer.MAX_VALUE);
// Entries are { effort, row, col }; break effort ties by row, then column.
PriorityQueue<int[]> pq = new PriorityQueue<>(
Comparator.<int[]>comparingInt(a -> a[0])
.thenComparingInt(a -> a[1]).thenComparingInt(a -> a[2]));
effort[0][0] = 0;
pq.offer(new int[] { 0, 0, 0 });
int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
while (true) {
int[] cur = pq.poll();
int e = cur[0], r = cur[1], c = cur[2];
if (e > effort[r][c]) continue; // a stale entry
if (r == rows - 1 && c == cols - 1) return e;
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
int next = Math.max(e, Math.abs(heights[nr][nc] - heights[r][c]));
if (next < effort[nr][nc]) {
effort[nr][nc] = next;
pq.offer(new int[] { next, nr, nc });
}
}
}
}Python
import heapq
def minimum_effort_path(heights):
rows, cols = len(heights), len(heights[0])
effort = [[float("inf")] * cols for _ in range(rows)]
effort[0][0] = 0
pq = [(0, 0, 0)] # (effort, row, col)
while True:
e, r, c = heapq.heappop(pq)
if e > effort[r][c]: # a stale entry
continue
if r == rows - 1 and c == cols - 1:
return e
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
nxt = max(e, abs(heights[nr][nc] - heights[r][c]))
if nxt < effort[nr][nc]:
effort[nr][nc] = nxt
heapq.heappush(pq, (nxt, nr, nc))C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minimumEffortPath(vector<vector<int>> &heights) {
int rows = int(heights.size()), cols = int(heights[0].size());
vector<vector<int>> effort(rows, vector<int>(cols, INT_MAX));
// Entries are { effort, row, col }, compared in that order.
priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
effort[0][0] = 0;
pq.push(vector<int>{0, 0, 0});
vector<vector<int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
while (true) {
vector<int> cur = pq.top();
pq.pop();
int e = cur[0], r = cur[1], c = cur[2];
if (e > effort[r][c])
continue;
if (r == rows - 1 && c == cols - 1)
return e;
for (vector<int> &d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr < 0 || nc < 0 || nr >= rows || nc >= cols)
continue;
int next = std::max(e, std::abs(heights[nr][nc] - heights[r][c]));
if (next < effort[nr][nc]) {
effort[nr][nc] = next;
pq.push(vector<int>{next, nr, nc});
}
}
}
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Max Area of Island (Medium)
- Rotting Oranges (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Path in Binary Matrix (Medium)
- Shortest Bridge (Medium)
- Shortest Path in a Grid with Obstacles Elimination (Hard)
- Surrounded Regions (Medium)
- Pacific Atlantic Water Flow (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)
- Swim in Rising Water (Hard)