|
| 1 | +/** |
| 2 | + * 1162. As Far from Land as Possible |
| 3 | + * https://leetcode.com/problems/as-far-from-land-as-possible/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents |
| 7 | + * land, find a water cell such that its distance to the nearest land cell is maximized, and return |
| 8 | + * the distance. If no land or water exists in the grid, return -1. |
| 9 | + * |
| 10 | + * The distance used in this problem is the Manhattan distance: the distance between two cells |
| 11 | + * (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number[][]} grid |
| 16 | + * @return {number} |
| 17 | + */ |
| 18 | +var maxDistance = function(grid) { |
| 19 | + const size = grid.length; |
| 20 | + const queue = []; |
| 21 | + let waterCount = 0; |
| 22 | + |
| 23 | + for (let row = 0; row < size; row++) { |
| 24 | + for (let col = 0; col < size; col++) { |
| 25 | + if (grid[row][col] === 1) { |
| 26 | + queue.push([row, col]); |
| 27 | + } else { |
| 28 | + waterCount++; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + if (waterCount === 0 || queue.length === 0) return -1; |
| 34 | + |
| 35 | + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; |
| 36 | + let distance = -1; |
| 37 | + |
| 38 | + while (queue.length > 0) { |
| 39 | + distance++; |
| 40 | + const levelSize = queue.length; |
| 41 | + for (let i = 0; i < levelSize; i++) { |
| 42 | + const [currentRow, currentCol] = queue.shift(); |
| 43 | + for (const [deltaRow, deltaCol] of directions) { |
| 44 | + const newRow = currentRow + deltaRow; |
| 45 | + const newCol = currentCol + deltaCol; |
| 46 | + if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size |
| 47 | + && grid[newRow][newCol] === 0) { |
| 48 | + grid[newRow][newCol] = 1; |
| 49 | + queue.push([newRow, newCol]); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return distance === 0 ? -1 : distance; |
| 56 | +}; |
0 commit comments