Approach
Breadth-first search
For Find the Safest Path in a Grid, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 87 lines of C++ from the credited upstream file 2812.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 8 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maximumSafenessFactor(vector<vector<int>>& grid) {4 const vector<vector<int>> distToThief = getDistToThief(grid);5 int l = 0;6 int r = grid.size() * 2;7 8 while (l < r) {9 const int m = (l + r) / 2;10 if (hasValidPath(distToThief, m))11 l = m + 1;12 else13 r = m;14 }15 16 return l - 1;17 }18 19 private:20 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};21 22 bool hasValidPath(const vector<vector<int>>& distToThief, int safeness) {23 if (distToThief[0][0] < safeness)24 return false;25 26 const int n = distToThief.size();27 queue<pair<int, int>> q{{{0, 0}}};28 vector<vector<bool>> seen(n, vector<bool>(n));29 seen[0][0] = true;30 31 while (!q.empty()) {32 const auto [i, j] = q.front();33 q.pop();34 if (distToThief[i][j] < safeness)35 continue;36 if (i == n - 1 && j == n - 1)37 return true;38 for (const auto& [dx, dy] : kDirs) {39 const int x = i + dx;40 const int y = j + dy;41 if (x < 0 || x == n || y < 0 || y == n)42 continue;43 if (seen[x][y])44 continue;45 q.emplace(x, y);46 seen[x][y] = true;47 }48 }49 50 return false;51 }52 53 vector<vector<int>> getDistToThief(const vector<vector<int>>& grid) {54 const int n = grid.size();55 vector<vector<int>> distToThief(n, vector<int>(n));56 queue<pair<int, int>> q;57 vector<vector<bool>> seen(n, vector<bool>(n));58 59 for (int i = 0; i < n; ++i)60 for (int j = 0; j < n; ++j)61 if (grid[i][j] == 1) {62 q.emplace(i, j);63 seen[i][j] = true;64 }65 66 for (int dist = 0; !q.empty(); ++dist) {67 for (int sz = q.size(); sz > 0; --sz) {68 const auto [i, j] = q.front();69 q.pop();70 distToThief[i][j] = dist;71 for (const auto& [dx, dy] : kDirs) {72 const int x = i + dx;73 const int y = j + dy;74 if (x < 0 || x == n || y < 0 || y == n)75 continue;76 if (seen[x][y])77 continue;78 q.emplace(x, y);79 seen[x][y] = true;80 }81 }82 }83 84 return distToThief;85 }86};87