Skip to content

2812. Find the Safest Path in a Grid 👍

  • Time: $O(n^2\log n)$
  • Space: $O(n^2)$
 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
class Solution {
 public:
  int maximumSafenessFactor(vector<vector<int>>& grid) {
    const vector<vector<int>> distToThief = getDistToThief(grid);
    int l = 0;
    int r = grid.size() * 2;

    while (l < r) {
      const int m = (l + r) / 2;
      if (hasValidPath(distToThief, m))
        l = m + 1;
      else
        r = m;
    }

    return l - 1;
  }

 private:
  static constexpr int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

  bool hasValidPath(const vector<vector<int>>& distToThief, int safeness) {
    if (distToThief[0][0] < safeness)
      return false;

    const int n = distToThief.size();
    queue<pair<int, int>> q{{{0, 0}}};
    vector<vector<bool>> seen(n, vector<bool>(n));
    seen[0][0] = true;

    while (!q.empty()) {
      const auto [i, j] = q.front();
      q.pop();
      if (distToThief[i][j] < safeness)
        continue;
      if (i == n - 1 && j == n - 1)
        return true;
      for (const auto& [dx, dy] : dirs) {
        const int x = i + dx;
        const int y = j + dy;
        if (x < 0 || x == n || y < 0 || y == n)
          continue;
        if (seen[x][y])
          continue;
        q.emplace(x, y);
        seen[x][y] = true;
      }
    }

    return false;
  }

  vector<vector<int>> getDistToThief(const vector<vector<int>>& grid) {
    const int n = grid.size();
    vector<vector<int>> distToThief(n, vector<int>(n));
    queue<pair<int, int>> q;
    vector<vector<bool>> seen(n, vector<bool>(n));

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        if (grid[i][j] == 1) {
          q.emplace(i, j);
          seen[i][j] = true;
        }

    for (int dist = 0; !q.empty(); ++dist) {
      for (int sz = q.size(); sz > 0; --sz) {
        const auto [i, j] = q.front();
        q.pop();
        distToThief[i][j] = dist;
        for (const auto& [dx, dy] : dirs) {
          const int x = i + dx;
          const int y = j + dy;
          if (x < 0 || x == n || y < 0 || y == n)
            continue;
          if (seen[x][y])
            continue;
          q.emplace(x, y);
          seen[x][y] = true;
        }
      }
    }

    return distToThief;
  }
};
 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
class Solution {
  public int maximumSafenessFactor(List<List<Integer>> grid) {
    int[][] distToThief = getDistToThief(grid);
    int l = 0;
    int r = grid.size() * 2;

    while (l < r) {
      final int m = (l + r) / 2;
      if (hasValidPath(distToThief, m))
        l = m + 1;
      else
        r = m;
    }

    return l - 1;
  }

  private static final int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

  private boolean hasValidPath(int[][] distToThief, int safeness) {
    if (distToThief[0][0] < safeness)
      return false;

    final int n = distToThief.length;
    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(0, 0)));
    boolean[][] seen = new boolean[n][n];
    seen[0][0] = true;

    while (!q.isEmpty()) {
      final int i = q.peek().getKey();
      final int j = q.poll().getValue();
      if (distToThief[i][j] < safeness)
        continue;
      if (i == n - 1 && j == n - 1)
        return true;
      for (int[] dir : dirs) {
        final int x = i + dir[0];
        final int y = j + dir[1];
        if (x < 0 || x == n || y < 0 || y == n)
          continue;
        if (seen[x][y])
          continue;
        q.offer(new Pair<>(x, y));
        seen[x][y] = true;
      }
    }

    return false;
  }

  private int[][] getDistToThief(List<List<Integer>> grid) {
    final int n = grid.size();
    int[][] distToThief = new int[n][n];
    Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();
    boolean[][] seen = new boolean[n][n];

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        if (grid.get(i).get(j) == 1) {
          q.offer(new Pair<>(i, j));
          seen[i][j] = true;
        }

    for (int dist = 0; !q.isEmpty(); ++dist) {
      for (int sz = q.size(); sz > 0; --sz) {
        final int i = q.peek().getKey();
        final int j = q.poll().getValue();
        distToThief[i][j] = dist;
        for (int[] dir : dirs) {
          final int x = i + dir[0];
          final int y = j + dir[1];
          if (x < 0 || x == n || y < 0 || y == n)
            continue;
          if (seen[x][y])
            continue;
          q.offer(new Pair<>(x, y));
          seen[x][y] = true;
        }
      }
    }

    return distToThief;
  }
}
 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
class Solution:
  def maximumSafenessFactor(self, grid: list[list[int]]) -> int:
    self.dirs = ((0, 1), (1, 0), (0, -1), (-1, 0))
    n = len(grid)
    distToThief = self._getDistToThief(grid)

    def hasValidPath(safeness: int) -> bool:
      if distToThief[0][0] < safeness:
        return False

      q = collections.deque([(0, 0)])
      seen = {(0, 0)}

      while q:
        i, j = q.popleft()
        if distToThief[i][j] < safeness:
          continue
        if i == n - 1 and j == n - 1:
          return True
        for dx, dy in self.dirs:
          x = i + dx
          y = j + dy
          if x < 0 or x == n or y < 0 or y == n:
            continue
          if (x, y) in seen:
            continue
          q.append((x, y))
          seen.add((x, y))

      return False

    return bisect.bisect_left(range(n * 2), True,
                              key=lambda m: not hasValidPath(m)) - 1

  def _getDistToThief(self, grid: list[list[int]]) -> list[list[int]]:
    n = len(grid)
    distToThief = [[0] * n for _ in range(n)]
    q = collections.deque()
    seen = set()

    for i in range(n):
      for j in range(n):
        if grid[i][j] == 1:
          q.append((i, j))
          seen.add((i, j))

    dist = 0
    while q:
      for _ in range(len(q)):
        i, j = q.popleft()
        distToThief[i][j] = dist
        for dx, dy in self.dirs:
          x = i + dx
          y = j + dy
          if x < 0 or x == n or y < 0 or y == n:
            continue
          if (x, y) in seen:
            continue
          q.append((x, y))
          seen.add((x, y))
      dist += 1

    return distToThief