|
| 1 | +/** |
| 2 | + * 778. Swim in Rising Water |
| 3 | + * https://leetcode.com/problems/swim-in-rising-water/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation |
| 7 | + * at that point (i, j). |
| 8 | + * |
| 9 | + * The rain starts to fall. At time t, the depth of the water everywhere is t. You can swim from |
| 10 | + * a square to another 4-directionally adjacent square if and only if the elevation of both squares |
| 11 | + * individually are at most t. You can swim infinite distances in zero time. Of course, you must |
| 12 | + * stay within the boundaries of the grid during your swim. |
| 13 | + * |
| 14 | + * Return the least time until you can reach the bottom right square (n - 1, n - 1) if you start |
| 15 | + * at the top left square (0, 0). |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[][]} grid |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var swimInWater = function(grid) { |
| 23 | + const n = grid.length; |
| 24 | + let left = grid[0][0]; |
| 25 | + let right = n * n - 1; |
| 26 | + |
| 27 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 28 | + |
| 29 | + const canReachDestination = (time) => { |
| 30 | + if (grid[0][0] > time) return false; |
| 31 | + |
| 32 | + const visited = Array(n).fill().map(() => Array(n).fill(false)); |
| 33 | + const queue = [[0, 0]]; |
| 34 | + visited[0][0] = true; |
| 35 | + |
| 36 | + while (queue.length > 0) { |
| 37 | + const [row, col] = queue.shift(); |
| 38 | + |
| 39 | + if (row === n - 1 && col === n - 1) { |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + for (const [dr, dc] of directions) { |
| 44 | + const newRow = row + dr; |
| 45 | + const newCol = col + dc; |
| 46 | + |
| 47 | + if ( |
| 48 | + newRow >= 0 && newRow < n && newCol >= 0 && newCol < n |
| 49 | + && !visited[newRow][newCol] && grid[newRow][newCol] <= time |
| 50 | + ) { |
| 51 | + queue.push([newRow, newCol]); |
| 52 | + visited[newRow][newCol] = true; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return false; |
| 58 | + }; |
| 59 | + |
| 60 | + while (left < right) { |
| 61 | + const mid = Math.floor((left + right) / 2); |
| 62 | + |
| 63 | + if (canReachDestination(mid)) { |
| 64 | + right = mid; |
| 65 | + } else { |
| 66 | + left = mid + 1; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return left; |
| 71 | +}; |
0 commit comments