|
| 1 | +/** |
| 2 | + * @param {number[][]} grid |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | +const maximumMinutes = function (grid) { |
| 6 | + const [m, n] = [grid.length, grid[0].length] |
| 7 | + const dir = [ |
| 8 | + [-1, 0], |
| 9 | + [1, 0], |
| 10 | + [0, -1], |
| 11 | + [0, 1], |
| 12 | + ] |
| 13 | + |
| 14 | + function isValidCell(x, y) { |
| 15 | + return x >= 0 && x < m && y >= 0 && y < n |
| 16 | + } |
| 17 | + |
| 18 | + const fireDist = new Array(m) |
| 19 | + for (let i = 0; i < m; i++) { |
| 20 | + fireDist[i] = new Array(n).fill(Infinity) |
| 21 | + } |
| 22 | + |
| 23 | + const firePoints = [] |
| 24 | + for (let i = 0; i < m; i++) { |
| 25 | + for (let j = 0; j < n; j++) { |
| 26 | + if (grid[i][j] === 1) { |
| 27 | + firePoints.push([i, j]) |
| 28 | + fireDist[i][j] = 0 |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + while (firePoints.length) { |
| 34 | + const [x0, y0] = firePoints.shift() |
| 35 | + |
| 36 | + for (const [dx, dy] of dir) { |
| 37 | + const [x1, y1] = [x0 + dx, y0 + dy] |
| 38 | + |
| 39 | + if ( |
| 40 | + isValidCell(x1, y1) && |
| 41 | + grid[x1][y1] === 0 && |
| 42 | + fireDist[x0][y0] + 1 < fireDist[x1][y1] |
| 43 | + ) { |
| 44 | + fireDist[x1][y1] = fireDist[x0][y0] + 1 |
| 45 | + firePoints.push([x1, y1]) |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + function canEscape(delay) { |
| 51 | + const visited = new Array(m) |
| 52 | + for (let i = 0; i < m; i++) { |
| 53 | + visited[i] = new Array(n).fill(false) |
| 54 | + } |
| 55 | + |
| 56 | + const queue = [[0, 0]] |
| 57 | + let currMinutes = delay |
| 58 | + |
| 59 | + while (queue.length) { |
| 60 | + currMinutes++ |
| 61 | + |
| 62 | + for (let i = queue.length; i > 0; i--) { |
| 63 | + const [i0, j0] = queue.shift() |
| 64 | + visited[i0][j0] = true |
| 65 | + |
| 66 | + for (const [di, dj] of dir) { |
| 67 | + const [i1, j1] = [i0 + di, j0 + dj] |
| 68 | + |
| 69 | + if ( |
| 70 | + isValidCell(i1, j1) && |
| 71 | + grid[i1][j1] === 0 && |
| 72 | + !visited[i1][j1] && |
| 73 | + (currMinutes < fireDist[i1][j1] || |
| 74 | + (currMinutes === fireDist[i1][j1] && |
| 75 | + i1 === m - 1 && |
| 76 | + j1 === n - 1)) |
| 77 | + ) { |
| 78 | + if (i1 === m - 1 && j1 === n - 1) { |
| 79 | + return true |
| 80 | + } |
| 81 | + queue.push([i1, j1]) |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return false |
| 88 | + } |
| 89 | + |
| 90 | + let [left, right] = [-1, 1_000_000_000] |
| 91 | + |
| 92 | + while (left < right) { |
| 93 | + const middle = Math.floor((left + right + 1) / 2) |
| 94 | + |
| 95 | + if (canEscape(middle)) { |
| 96 | + left = middle |
| 97 | + } else { |
| 98 | + right = middle - 1 |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + return left |
| 103 | +} |
0 commit comments