

var orangesRotting = function (grid) {
const m = grid.length
const n = grid[0].length
const queue = []
let fresh = 0
let time = 0
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (grid[i][j] === 2) {
queue.push([i, j])
} else if (grid[i][j] === 1) {
fresh++
}
}
}
const del = [
[0, 1],
[0, -1],
[-1, 0],
[1, 0],
]
while (queue.length && fresh) {
const len = queue.length
for (let i = 0; i < len; i++) {
const item = queue.shift()
for (let j = 0; j < 4; j++) {
const x = item[0] + del[j][0]
const y = item[1] + del[j][1]
if (grid[x] && grid[x][y] && grid[x][y] === 1) {
fresh--
queue.push([x, y])
grid[x][y] = 2
}
}
}
time++
}
return fresh === 0 ? time : -1
}
994. 腐烂的橘子 - 力扣(LeetCode)