1
var maximumMinutes = function (grid) {2
let fireSpread = getFireSpreadTime(grid);6
let mid = Math.ceil((low + high) / 2);7
if (canReachSafehouse(grid, fireSpread, mid)) low = mid;10
return canReachSafehouse(grid, fireSpread, low) ? low : -1;13
function canReachSafehouse(originalGrid, fireSpread, timeToWait) {20
let grid = originalGrid.map((row) => [...row]);25
while (queue.length) {26
for (let i = queue.length; i > 0; i--) {27
let [row, col] = queue.shift();28
if (row === m - 1 && col === n - 1) {31
for (let [x, y] of directions) {39
grid[newX][newY] !== 041
continue; // out of bounds or cell is not grass42
let isTarget = newX === m - 1 && newY === n - 1;44
(isTarget && time + 1 <= fireSpread[newX][newY]) ||45
time + 1 < fireSpread[newX][newY]47
// only visit if fire will not spread to new cell at the next minute49
queue.push([newX, newY]);58
function getFireSpreadTime(originalGrid) {65
let grid = originalGrid.map((row) => [...row]);69
for (let i = 0; i < m; i++) {70
for (let j = 0; j < n; j++) {71
if (grid[i][j] === 1) {80
.map(() => Array(n).fill(Infinity));81
while (queue.length) {82
for (let i = queue.length; i > 0; i--) {83
let [row, col] = queue.shift();84
fireSpread[row][col] = time;85
for (let [x, y] of directions) {93
grid[newX][newY] !== 095
continue; // out of bounds or cell is not grass97
queue.push([newX, newY]);