Find the Safest Path in a Grid (LeetCode 2812): Solution and Explanation
Thieves sit on some cells of an n x n grid. Walk from the top-left to the bottom-right corner so that the closest you ever get to a thief is as far as possible, and return that distance.
Intuition
The safety of a single cell only depends on its nearest thief. So the problem splits in two: label every cell with that distance, then pick a route.
Labelling is a classic multi-source BFS. Start a BFS from all thieves at once; the layer in which a cell is reached is its distance to the nearest thief.
Once cells have labels, a route is only as safe as its lowest label. This is a widest-path problem: like Dijkstra, but you always expand the waiting cell with the highest reachable safety, and a step can only keep or lower the running minimum.
Labels are small integers (at most 2n), so instead of a heap you can drop waiting cells into buckets by safety and drain the buckets from the top down. Picture the safety level as a water line that only sinks when you are stuck.
Approach: Multi-source BFS + bucket flood
- Put every thief in a queue with distance 0 and run BFS to fill
distfor all cells. - Create buckets 0 to 2n - 1. Mark (0, 0) as seen and put it in bucket
dist[0][0]. - For level from
dist[0][0]down to 0, pop cells from bucketleveluntil it is empty. - If the popped cell is the bottom-right corner, return
level. - Otherwise push every unseen neighbor into bucket
min(level, dist[neighbor])and mark it seen.
Step-by-step example
grid = [[1,0,0],[0,0,0],[0,0,1]]
- Thieves at (0, 0) and (2, 2) get distance 0. The BFS labels the grid [[0,1,2],[1,2,1],[2,1,0]].
- The start (0, 0) has distance 0, so no route can beat 0. It goes into bucket 0 and the level starts at 0.
- Expanding at level 0, every neighbor also lands in bucket min(0, d) = 0.
- The flood eventually pops (2, 2) from bucket 0, so the answer is 0.
Code: Python, Java, C++
1class Solution:
2 def maximumSafenessFactor(self, grid: List[List[int]]) -> int:
3 n = len(grid)
4 dist = [[-1] * n for _ in range(n)]
5 queue = deque()
6 for r in range(n):
7 for c in range(n):
8 if grid[r][c] == 1:
9 dist[r][c] = 0
10 queue.append((r, c))
11 dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
12 while queue:
13 r, c = queue.popleft()
14 for dr, dc in dirs:
15 nr, nc = r + dr, c + dc
16 if 0 <= nr < n and 0 <= nc < n and dist[nr][nc] == -1:
17 dist[nr][nc] = dist[r][c] + 1
18 queue.append((nr, nc))
19 buckets = [[] for _ in range(2 * n)]
20 seen = [[False] * n for _ in range(n)]
21 seen[0][0] = True
22 buckets[dist[0][0]].append((0, 0))
23 for level in range(dist[0][0], -1, -1):
24 while buckets[level]:
25 r, c = buckets[level].pop()
26 if r == n - 1 and c == n - 1:
27 return level
28 for dr, dc in dirs:
29 nr, nc = r + dr, c + dc
30 if 0 <= nr < n and 0 <= nc < n and not seen[nr][nc]:
31 seen[nr][nc] = True
32 buckets[min(level, dist[nr][nc])].append((nr, nc))
33 return 01class Solution {
2 public int maximumSafenessFactor(int[][] grid) {
3 int n = grid.length;
4 int[][] dist = new int[n][n];
5 Deque<int[]> queue = new ArrayDeque<>();
6 for (int r = 0; r < n; r++) {
7 for (int c = 0; c < n; c++) {
8 dist[r][c] = grid[r][c] == 1 ? 0 : -1;
9 if (grid[r][c] == 1) queue.offer(new int[]{r, c});
10 }
11 }
12 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
13 while (!queue.isEmpty()) {
14 int[] cell = queue.poll();
15 for (int[] d : dirs) {
16 int nr = cell[0] + d[0], nc = cell[1] + d[1];
17 if (nr >= 0 && nr < n && nc >= 0 && nc < n && dist[nr][nc] == -1) {
18 dist[nr][nc] = dist[cell[0]][cell[1]] + 1;
19 queue.offer(new int[]{nr, nc});
20 }
21 }
22 }
23 List<List<int[]>> buckets = new ArrayList<>();
24 for (int i = 0; i < 2 * n; i++) buckets.add(new ArrayList<>());
25 boolean[][] seen = new boolean[n][n];
26 seen[0][0] = true;
27 buckets.get(dist[0][0]).add(new int[]{0, 0});
28 for (int level = dist[0][0]; level >= 0; level--) {
29 List<int[]> bucket = buckets.get(level);
30 while (!bucket.isEmpty()) {
31 int[] cell = bucket.remove(bucket.size() - 1);
32 if (cell[0] == n - 1 && cell[1] == n - 1) return level;
33 for (int[] d : dirs) {
34 int nr = cell[0] + d[0], nc = cell[1] + d[1];
35 if (nr >= 0 && nr < n && nc >= 0 && nc < n && !seen[nr][nc]) {
36 seen[nr][nc] = true;
37 buckets.get(Math.min(level, dist[nr][nc])).add(new int[]{nr, nc});
38 }
39 }
40 }
41 }
42 return 0;
43 }
44}1class Solution {
2public:
3 int maximumSafenessFactor(vector<vector<int>>& grid) {
4 int n = grid.size();
5 vector<vector<int>> dist(n, vector<int>(n, -1));
6 queue<pair<int, int>> q;
7 for (int r = 0; r < n; r++) {
8 for (int c = 0; c < n; c++) {
9 if (grid[r][c] == 1) {
10 dist[r][c] = 0;
11 q.push({r, c});
12 }
13 }
14 }
15 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
16 while (!q.empty()) {
17 auto [r, c] = q.front();
18 q.pop();
19 for (auto& d : dirs) {
20 int nr = r + d[0], nc = c + d[1];
21 if (nr >= 0 && nr < n && nc >= 0 && nc < n && dist[nr][nc] == -1) {
22 dist[nr][nc] = dist[r][c] + 1;
23 q.push({nr, nc});
24 }
25 }
26 }
27 vector<vector<pair<int, int>>> buckets(2 * n);
28 vector<vector<bool>> seen(n, vector<bool>(n, false));
29 seen[0][0] = true;
30 buckets[dist[0][0]].push_back({0, 0});
31 for (int level = dist[0][0]; level >= 0; level--) {
32 while (!buckets[level].empty()) {
33 auto [r, c] = buckets[level].back();
34 buckets[level].pop_back();
35 if (r == n - 1 && c == n - 1) return level;
36 for (auto& d : dirs) {
37 int nr = r + d[0], nc = c + d[1];
38 if (nr >= 0 && nr < n && nc >= 0 && nc < n && !seen[nr][nc]) {
39 seen[nr][nc] = true;
40 buckets[min(level, dist[nr][nc])].push_back({nr, nc});
41 }
42 }
43 }
44 }
45 return 0;
46 }
47};Time and space complexity
O(n^2)
The BFS visits each cell once. The flood pushes each cell into exactly one bucket and pops it once, and the level loop runs at most 2n times.
O(n^2)
The distance grid, the seen grid and the buckets each hold up to n^2 entries.
Other approaches
Max-heap Dijkstra (time O(n^2 log n), space O(n^2))
Same idea with a priority queue keyed by the running minimum. Simpler to explain, with an extra log factor.
Binary search on the answer (time O(n^2 log n), space O(n^2))
For a candidate k, check with BFS whether the corners are connected using only cells with distance at least k. Binary search k between 0 and 2n.
Union-find in decreasing order (time O(n^2 log n), space O(n^2))
Sort cells by distance, add them from safest to least safe and union each with already added neighbors. The distance at which the two corners join is the answer.
Common mistakes
- Running a separate BFS from every thief. With many thieves that is O(n^4); one BFS seeded with all of them is enough.
- Treating it as a shortest path problem. Path length does not matter, only the lowest distance along the route.
- Forgetting the start and end cells. They are on every path, so the answer can never exceed min(dist[0][0], dist[n-1][n-1]).
- Pushing a neighbor with its own distance instead of min(level, distance). The route's safety is the minimum along it, so it can never go back up.
Frequently asked questions
Why is it safe to mark a cell seen when it is pushed, not when it is popped?
Buckets are drained from high to low. The first time a cell is pushed, the current level is the highest it will ever be, so min(level, dist) is already the best key that cell can get.
Why are there at most 2n buckets?
The largest Manhattan distance inside an n x n grid is 2(n - 1), so every distance fits in buckets 0 to 2n - 1.
Can the path walk over a thief?
Yes, moves onto thief cells are allowed. Doing so just makes the safeness factor 0.
What if n is 1?
The single cell must hold the thief, so the start is the end and the answer is 0.