[LeetCode] Find the Safest Path in a Grid

2812. Find the Safest Path in a Grid

You are given a 0-indexed 2D matrix grid of size n x n, where (r, c) represents:

  • A cell containing a thief if grid[r][c] = 1
  • An empty cell if grid[r][c] = 0

You are initially positioned at cell (0, 0). In one move, you can move to any adjacent cell in the grid, including cells containing thieves.

The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid.

Return the maximum safeness factor of all paths leading to cell (n - 1, n - 1).

An adjacent cell of cell (r, c), is one of the cells (r, c + 1), (r, c - 1), (r + 1, c) and (r - 1, c) if it exists.

The Manhattan distance between two cells (a, b) and (x, y) is equal to |a - x| + |b - y|, where |val| denotes the absolute value of val.

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
class Solution {
int dy[4]{-1,0,1,0}, dx[4]{0,1,0,-1};
bool bfs(vector<vector<int>>& A, int k) {
int n = A.size(), m = A[0].size();
vector<vector<int>> vis(n,vector<int>(m));
queue<pair<int, int>> q;
auto push = [&](int y, int x) {
if(A[y][x] >= k and !vis[y][x]) {
q.push({y,x});
vis[y][x] = true;
}
};
push(0,0);
while(q.size()) {
auto [y,x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m) {
push(ny,nx);
}
}
}
return vis[n-1][m-1];
}
public:
int maximumSafenessFactor(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
vector<vector<int>> safe(n, vector<int>(m, -1));
queue<pair<int, int>> q;
auto push =[&](int y, int x, int c) {
if(safe[y][x] == -1) {
safe[y][x] = c;
q.push({y,x});
}
};
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
if(A[i][j]) push(i,j,0);
}
while(q.size()) {
auto [y,x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m) {
push(ny,nx,safe[y][x] + 1);
}
}
}
int l = 0, r = n + m, res = l;
while(l <= r) {
int m = l + (r - l) / 2;
bool ok = bfs(safe,m);
if(ok) {
res = max(res, m);
l = m + 1;
} else r = m - 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/06/PS/LeetCode/find-the-safest-path-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.