|
| 1 | +/** |
| 2 | + * 994. Rotting Oranges |
| 3 | + * https://leetcode.com/problems/rotting-oranges/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an m x n grid where each cell can have one of three values: |
| 7 | + * - 0 representing an empty cell, |
| 8 | + * - 1 representing a fresh orange, or |
| 9 | + * - 2 representing a rotten orange. |
| 10 | + * |
| 11 | + * Every minute, any fresh orange that is 4-directionally adjacent to a rotten |
| 12 | + * orange becomes rotten. |
| 13 | + * |
| 14 | + * Return the minimum number of minutes that must elapse until no cell has a |
| 15 | + * fresh orange. If this is impossible, return -1. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[][]} grid |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var orangesRotting = function(grid) { |
| 23 | + const queue = []; |
| 24 | + let count = 0; |
| 25 | + |
| 26 | + for (let i = 0; i < grid.length; i++) { |
| 27 | + for (let j = 0; j < grid[0].length; j++) { |
| 28 | + if (grid[i][j] === 2) { |
| 29 | + queue.push([i, j, 0]); |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + while (queue.length) { |
| 35 | + const [i, j, k] = queue.shift(); |
| 36 | + [[-1, 0], [1, 0], [0, -1], [0, 1]].forEach(p => { |
| 37 | + const [x, y, z] = [i + p[0], j + p[1], k + 1]; |
| 38 | + if (x > -1 && x < grid.length && y > -1 && y < grid[0].length) { |
| 39 | + if (grid[x][y] === 1) { |
| 40 | + grid[x][y] = 2; |
| 41 | + count = Math.max(count, z); |
| 42 | + queue.push([x, y, z]); |
| 43 | + } |
| 44 | + } |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + const isIncomplete = grid.some(row => row.some(n => n === 1)); |
| 49 | + return isIncomplete ? -1 : count; |
| 50 | +}; |
0 commit comments