1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| class Solution { static int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int m, n; boolean flag; int[][] grid, fire, people;
public int maximumMinutes(int[][] grid) { this.grid = grid; m = grid.length; n = grid[0].length; fire = new int[m][n]; people = new int[m][n]; if (!check(0)) return -1; int left = 0, right = m * n; while (left < right) { int mid = left + right + 1 >> 1; if (check(mid)) left = mid; else right = mid - 1; } return right == m * n ? (int) 1e9 : right; }
private boolean check(int t) { flag = false; Deque<int[]> fd = new ArrayDeque<>(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { fire[i][j] = people[i][j] = 0; if (grid[i][j] == 1) { fire[i][j] = 1; fd.offer(new int[]{i, j}); } } } while (t-- > 0) { update(fd, true, 0); } if (fire[0][0] != 0) return false; Deque<int[]> pd = new ArrayDeque<>(); people[0][0] = 1; pd.offer(new int[]{0, 0}); while (!pd.isEmpty()) { update(fd, true, 1); update(pd, false, 1); if (flag) return true; } return false; }
private void update(Deque<int[]> queue, boolean isFire, int offset) { int size = queue.size(); while (size-- > 0) { int[] cur = queue.poll(); int x = cur[0], y = cur[1]; for (int[] dir : dirs) { int nx = x + dir[0], ny = y + dir[1]; if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue; if (grid[nx][ny] == 2) continue; if (isFire) { if (fire[nx][ny] != 0) continue; fire[nx][ny] = fire[x][y] + offset; } else { if (nx == m - 1 && ny == n - 1 && (fire[nx][ny] == 0 || fire[nx][ny] == people[x][y] + offset)) flag = true; if (fire[nx][ny] != 0 || people[nx][ny] != 0) continue; people[nx][ny] = people[x][y] + offset; } queue.offer(new int[]{nx, ny}); } } } }
|