Skip to content

2258. Escape the Spreading Fire 👍

  • Time: $O(mn\log mn)$
  • Space: $O(mn)$
 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Solution {
 public:
  int maximumMinutes(vector<vector<int>>& grid) {
    const vector<int> dirs{0, 1, 0, -1, 0};
    const int kMax = grid.size() * grid[0].size();
    vector<vector<int>> fireMinute(grid.size(),
                                   vector<int>(grid[0].size(), -1));
    buildFireGrid(grid, fireMinute, dirs);

    int ans = -1;
    int l = 0;
    int r = kMax;

    while (l <= r) {
      const int m = (l + r) / 2;
      if (canStayFor(grid, fireMinute, m, dirs)) {
        ans = m;
        l = m + 1;
      } else {
        r = m - 1;
      }
    }

    return ans == kMax ? 1e9 : ans;
  }

 private:
  void buildFireGrid(const vector<vector<int>>& grid,
                     vector<vector<int>>& fireMinute, const vector<int>& dirs) {
    int minuteFromFire = 0;
    queue<pair<int, int>> q;

    for (int i = 0; i < grid.size(); ++i)
      for (int j = 0; j < grid[0].size(); ++j)
        if (grid[i][j] == 1) {  // Fire
          q.emplace(i, j);
          fireMinute[i][j] = 0;
        }

    while (!q.empty()) {
      ++minuteFromFire;
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [i, j] = q.front();
        q.pop();
        for (int k = 0; k < 4; ++k) {
          const int x = i + dirs[k];
          const int y = j + dirs[k + 1];
          if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size())
            continue;
          if (grid[x][y] == 2)  // Wall
            continue;
          if (fireMinute[x][y] != -1)
            continue;
          fireMinute[x][y] = minuteFromFire;
          q.emplace(x, y);
        }
      }
    }
  }

  bool canStayFor(const vector<vector<int>>& grid,
                  const vector<vector<int>>& fireMinute, int minute,
                  const vector<int>& dirs) {
    queue<pair<int, int>> q{{{0, 0}}};  // Start position
    vector<vector<bool>> seen(grid.size(), vector<bool>(grid[0].size()));
    seen[0][0] = true;

    while (!q.empty()) {
      ++minute;
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [i, j] = q.front();
        q.pop();
        for (int k = 0; k < 4; ++k) {
          const int x = i + dirs[k];
          const int y = j + dirs[k + 1];
          if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size())
            continue;
          if (grid[x][y] == 2)  // Wall
            continue;
          if (x == grid.size() - 1 && y == grid[0].size() - 1) {
            if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute)
              continue;
            return true;
          }
          if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute)
            continue;
          if (seen[x][y])
            continue;
          q.emplace(x, y);
          seen[x][y] = true;
        }
      }
    }

    return false;
  }
};
 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Solution {
  public int maximumMinutes(int[][] grid) {
    final int[] dirs = {0, 1, 0, -1, 0};
    final int kMax = grid.length * grid[0].length;
    int[][] fireMinute = new int[grid.length][grid[0].length];
    Arrays.stream(fireMinute).forEach(A -> Arrays.fill(A, -1));
    buildFireGrid(grid, fireMinute, dirs);

    int ans = -1;
    int l = 0;
    int r = kMax;

    while (l <= r) {
      final int m = (l + r) / 2;
      if (canStayFor(grid, fireMinute, m, dirs)) {
        ans = m;
        l = m + 1;
      } else {
        r = m - 1;
      }
    }

    return ans == kMax ? (int) 1e9 : ans;
  }

  private void buildFireGrid(int[][] grid, int[][] fireMinute, final int[] dirs) {
    int minuteFromFire = 0;
    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();

    for (int i = 0; i < grid.length; ++i)
      for (int j = 0; j < grid[0].length; ++j)
        if (grid[i][j] == 1) { // Fire
          q.offer(new Pair<>(i, j));
          fireMinute[i][j] = 0;
        }

    while (!q.isEmpty()) {
      ++minuteFromFire;
      for (int sz = q.size(); sz > 0; --sz) {
        final int i = q.peek().getKey();
        final int j = q.poll().getValue();
        for (int k = 0; k < 4; ++k) {
          final int x = i + dirs[k];
          final int y = j + dirs[k + 1];
          if (x < 0 || x == grid.length || y < 0 || y == grid[0].length)
            continue;
          if (grid[x][y] == 2) // Wall
            continue;
          if (fireMinute[x][y] != -1)
            continue;
          fireMinute[x][y] = minuteFromFire;
          q.offer(new Pair<>(x, y));
        }
      }
    }
  }

  boolean canStayFor(int[][] grid, int[][] fireMinute, int minute, final int[] dirs) {
    Queue<Pair<Integer, Integer>> q =
        new ArrayDeque<>(Arrays.asList(new Pair<>(0, 0))); // Start position
    boolean[][] seen = new boolean[grid.length][grid[0].length];
    seen[0][0] = true;

    while (!q.isEmpty()) {
      ++minute;
      for (int sz = q.size(); sz > 0; --sz) {
        final int i = q.peek().getKey();
        final int j = q.poll().getValue();
        for (int k = 0; k < 4; ++k) {
          final int x = i + dirs[k];
          final int y = j + dirs[k + 1];
          if (x < 0 || x == grid.length || y < 0 || y == grid[0].length)
            continue;
          if (grid[x][y] == 2) // Wall
            continue;
          if (x == grid.length - 1 && y == grid[0].length - 1) {
            if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute)
              continue;
            return true;
          }
          if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute)
            continue;
          if (seen[x][y])
            continue;
          q.offer(new Pair<>(x, y));
          seen[x][y] = true;
        }
      }
    }

    return false;
  }
}
 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
class Solution:
  def maximumMinutes(self, grid: List[List[int]]) -> int:
    dirs = [0, 1, 0, -1, 0]
    kMax = len(grid) * len(grid[0])
    fireGrid = [[-1] * len(grid[0]) for _ in range(len(grid[0]))]
    self._buildFireGrid(grid, fireGrid, dirs)

    ans = -1
    l = 0
    r = kMax

    while l <= r:
      m = (l + r) // 2
      if self._canStayFor(grid, fireGrid, m, dirs):
        ans = m
        l = m + 1
      else:
        r = m - 1

    return 1e9 if ans == kMax else ans

  def _buildFireGrid(self, grid: List[List[int]], fireMinute: List[List[int]], dirs: List[int]) -> None:
    minuteFromFire = 0
    q = collections.deque()

    for i in range(len(grid)):
      for j in range(len(grid[0])):
        if grid[i][j] == 1:  # Fire
          q.append((i, j))
          fireMinute[i][j] = 0

    while q:
      minuteFromFire += 1
      for _ in range(len(q)):
        i, j = q.popleft()
        for k in range(4):
          x = i + dirs[k]
          y = j + dirs[k + 1]
          if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):
            continue
          if grid[x][y] == 2:  # Wall
            continue
          if fireMinute[x][y] != -1:
            continue
          fireMinute[x][y] = minuteFromFire
          q.append((x, y))

  def _canStayFor(self, grid: List[List[int]], fireMinute: List[List[int]], minute: int, dirs: List[int]) -> bool:
    q = collections.deque([(0, 0)])  # Start position
    seen = {(0, 0)}

    while q:
      minute += 1
      for _ in range(len(q)):
        i, j = q.popleft()
        for k in range(4):
          x = i + dirs[k]
          y = j + dirs[k + 1]
          if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]):
            continue
          if grid[x][y] == 2:  # Wall
            continue
          if x == len(grid) - 1 and y == len(grid[0]) - 1:
            if fireMinute[x][y] != -1 and fireMinute[x][y] < minute:
              continue
            return True
          if fireMinute[x][y] != -1 and fireMinute[x][y] <= minute:
            continue
          if seen[x][y]:
            continue
          q.append((x, y))
          seen.add((x, y))

    return False