⬅ Previous Topic
Shortest Distance in a Binary Maze using BFSNext Topic ⮕
Cheapest Flights Within K Stops - Graph Problem⬅ Previous Topic
Shortest Distance in a Binary Maze using BFSNext Topic ⮕
Cheapest Flights Within K Stops - Graph ProblemTopic Contents
Imagine you're a hiker navigating a mountainous terrain. You're given a 2D grid heights
of dimensions rows × columns
, where each element represents the elevation at that cell.
Your goal is to move from the top-left corner (0, 0)
to the bottom-right corner (rows-1, columns-1)
, moving only up, down, left, or right at each step.
The effort of a path is defined as the maximum absolute difference in heights between any two adjacent cells on that path. Your task is to find the path that minimizes this effort.
efforts
with Infinity
and set efforts[0][0] = 0
.function minimumEffortPath(heights) {
const rows = heights.length;
const cols = heights[0].length;
const directions = [[0,1],[1,0],[-1,0],[0,-1]];
const efforts = Array.from({ length: rows }, () => Array(cols).fill(Infinity));
const heap = [[0, 0, 0]]; // [effort, x, y]
efforts[0][0] = 0;
while (heap.length > 0) {
heap.sort((a, b) => a[0] - b[0]);
const [effort, x, y] = heap.shift();
if (x === rows - 1 && y === cols - 1) return effort;
for (const [dx, dy] of directions) {
const nx = x + dx;
const ny = y + dy;
if (nx >= 0 && ny >= 0 && nx < rows && ny < cols) {
const diff = Math.abs(heights[nx][ny] - heights[x][y]);
const maxEffort = Math.max(effort, diff);
if (maxEffort < efforts[nx][ny]) {
efforts[nx][ny] = maxEffort;
heap.push([maxEffort, nx, ny]);
}
}
}
}
return -1;
}
const heights = [[1,2,2],[3,8,2],[5,3,5]];
console.log("Minimum Effort:", minimumEffortPath(heights));
⬅ Previous Topic
Shortest Distance in a Binary Maze using BFSNext Topic ⮕
Cheapest Flights Within K Stops - Graph ProblemYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.