Approach
Breadth-first search
For Find a Safe Walk Through 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
- 36 lines of C++ from the credited upstream file 3286.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 3 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 bool findSafeWalk(vector<vector<int>>& grid, int health) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 const int m = grid.size();6 const int n = grid[0].size();7 const int initialHealth = health - grid[0][0];8 using T = tuple<int, int, int>; 9 queue<T> q{{{0, 0, initialHealth}}};10 vector<vector<vector<bool>>> seen(11 m, vector<vector<bool>>(n, vector<bool>(health + 1)));12 seen[0][0][initialHealth] = true;13 14 while (!q.empty())15 for (int sz = q.size(); sz > 0; --sz) {16 const auto [i, j, h] = q.front();17 q.pop();18 if (i == m - 1 && j == n - 1 && h > 0)19 return true;20 for (const auto& [dx, dy] : kDirs) {21 const int x = i + dx;22 const int y = j + dy;23 if (x < 0 || x == m || y < 0 || y == n)24 continue;25 const int nextHealth = h - grid[x][y];26 if (nextHealth <= 0 || seen[x][y][nextHealth])27 continue;28 q.emplace(x, y, nextHealth);29 seen[x][y][nextHealth] = true;30 }31 }32 33 return false;34 }35};36