|
| 1 | +/** |
| 2 | + * 1631. Path With Minimum Effort |
| 3 | + * https://leetcode.com/problems/path-with-minimum-effort/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size |
| 7 | + * rows x columns, where heights[row][col] represents the height of cell (row, col). You are |
| 8 | + * situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, |
| 9 | + * (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish |
| 10 | + * to find a route that requires the minimum effort. |
| 11 | + * |
| 12 | + * A route's effort is the maximum absolute difference in heights between two consecutive |
| 13 | + * cells of the route. |
| 14 | + * |
| 15 | + * Return the minimum effort required to travel from the top-left cell to the bottom-right cell. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[][]} heights |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var minimumEffortPath = function(heights) { |
| 23 | + const rows = heights.length; |
| 24 | + const cols = heights[0].length; |
| 25 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 26 | + |
| 27 | + function canReach(maxEffort) { |
| 28 | + const visited = Array.from({ length: rows }, () => Array(cols).fill(false)); |
| 29 | + const queue = [[0, 0]]; |
| 30 | + visited[0][0] = true; |
| 31 | + |
| 32 | + while (queue.length) { |
| 33 | + const [row, col] = queue.shift(); |
| 34 | + if (row === rows - 1 && col === cols - 1) return true; |
| 35 | + |
| 36 | + for (const [dr, dc] of directions) { |
| 37 | + const newRow = row + dr; |
| 38 | + const newCol = col + dc; |
| 39 | + |
| 40 | + if (newRow >= 0 && newRow < rows && newCol >= 0 |
| 41 | + && newCol < cols && !visited[newRow][newCol]) { |
| 42 | + const effort = Math.abs(heights[newRow][newCol] - heights[row][col]); |
| 43 | + if (effort <= maxEffort) { |
| 44 | + visited[newRow][newCol] = true; |
| 45 | + queue.push([newRow, newCol]); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + let left = 0; |
| 54 | + let right = 1000000; |
| 55 | + let result = right; |
| 56 | + |
| 57 | + while (left <= right) { |
| 58 | + const mid = Math.floor((left + right) / 2); |
| 59 | + if (canReach(mid)) { |
| 60 | + result = mid; |
| 61 | + right = mid - 1; |
| 62 | + } else { |
| 63 | + left = mid + 1; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return result; |
| 68 | +}; |
0 commit comments