2
public int maximumMinutes(int[][] grid) {4
int n = grid[0].length;6
int[][] times = new int[m][n];7
for (int[] row : times) {8
Arrays.fill(row, Integer.MAX_VALUE);11
int[] dir = new int[] {-1, 0, 1, 0, -1};13
// Queue for running BFS14
Deque<int[]> fires = new ArrayDeque<>();16
for (int row = 0; row < m; row++) {17
for (int col = 0; col < n; col++) {18
if (grid[row][col] == 1) {20
fires.offer(new int[] {row, col});26
while (!fires.isEmpty()) {27
int size = fires.size();29
for (int i = 0; i < size; i++) {30
int[] pos = fires.poll();32
for (int j = 0; j < 4; j++) {33
int x = pos[0] + dir[j];34
int y = pos[1] + dir[j + 1];41
&& times[x][y] == Integer.MAX_VALUE) {43
fires.offer(new int[] {x, y});53
int ans = Integer.MAX_VALUE;54
fires.offer(new int[] {0, 0});58
while (!fires.isEmpty() && grid[m - 1][n - 1] == 0) {59
int size = fires.size();61
int t = Integer.MIN_VALUE;63
for (int i = 0; i < size && grid[m - 1][n - 1] == 0; i++) {64
int[] pos = fires.poll();66
for (int j = 0; j < 4 && grid[m - 1][n - 1] == 0; j++) {68
int x = pos[0] + dir[j];69
int y = pos[1] + dir[j + 1];71
if (x >= 0 && y >= 0 && x < m && y < n && grid[x][y] == 0 && times[x][y] >= time) {72
if (x == m - 1 && y == n - 1) {73
t = times[x][y] - time;79
fires.offer(new int[] {x, y});81
// if times[x][y] == Integer.MAX_VALUE, fire will never reach this cell and it will82
// contribute maximum wait time83
t = Math.max(t, times[x][y] == Integer.MAX_VALUE ? 1000000000 : times[x][y] - time - 1);88
ans = Math.min(ans, t);93
// You can never reach the safe house94
if (grid[m - 1][n - 1] != 2) {98
// you can reach the safe house but fire can not99
if (times[m - 1][n - 1] == Integer.MAX_VALUE) {103
return ans == Integer.MAX_VALUE || ans == Integer.MIN_VALUE ? -1 : ans;