Created
December 7, 2022 18:55
-
-
Save zakkates/d1d9faed9588997c1b4c48a9f93b375f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[][]} grid | |
* @return {number} | |
*/ | |
var orangesRotting = function (grid) { | |
let totalOranges = 0, | |
rottenOranges = 0, | |
elapsedMinutes = 0, | |
width = grid[0].length, | |
height = grid.length; | |
const orangesToScan = []; | |
for (let i = 0; i < grid.length; i++) { | |
for (let j = 0; j < grid[0].length; j++) { | |
if (grid[i][j] == 2) { | |
orangesToScan.push([i, j]); | |
rottenOranges++; | |
totalOranges++; | |
} | |
if (grid[i][j] == 1) { | |
totalOranges++; | |
} | |
} | |
} | |
if (rottenOranges == totalOranges) return elapsedMinutes; | |
while (orangesToScan.length && rottenOranges < totalOranges) { | |
let lookForAdjacentOranges = orangesToScan.splice(0, orangesToScan.length); | |
while (lookForAdjacentOranges.length) { | |
let [row, col] = lookForAdjacentOranges.pop(); | |
// up | |
if (row > 0 && grid[row - 1][col] == 1) { | |
grid[row - 1][col] = 2; | |
rottenOranges++; | |
orangesToScan.push([row - 1, col]); | |
} | |
// down | |
if (row < height - 1 && grid[row + 1][col] == 1) { | |
grid[row + 1][col] = 2; | |
rottenOranges++; | |
orangesToScan.push([row + 1, col]); | |
} | |
// left | |
if (col > 0 && grid[row][col - 1] == 1) { | |
grid[row][col - 1] = 2; | |
rottenOranges++; | |
orangesToScan.push([row, col - 1]); | |
} | |
// right | |
if (col < width - 1 && grid[row][col + 1] == 1) { | |
grid[row][col + 1] = 2; | |
rottenOranges++; | |
orangesToScan.push([row, col + 1]); | |
} | |
} | |
elapsedMinutes++; | |
} | |
return (rottenOranges == totalOranges) ? elapsedMinutes : -1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment