Approach
Breadth-first search
For Shortest Path in a Grid with Obstacles Elimination, 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
- 39 lines of C++ from the credited upstream file 1293.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 int shortestPath(vector<vector<int>>& grid, int k) {4 const int m = grid.size();5 const int n = grid[0].size();6 if (m == 1 && n == 1)7 return 0;8 9 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};10 queue<tuple<int, int, int>> q{{{0, 0, k}}}; 11 vector<vector<vector<bool>>> seen(12 m, vector<vector<bool>>(n, vector<bool>(k + 1)));13 seen[0][0][k] = true;14 15 for (int step = 1; !q.empty(); ++step)16 for (int sz = q.size(); sz > 0; --sz) {17 const auto [i, j, eliminate] = q.front();18 q.pop();19 for (const auto& [dx, dy] : kDirs) {20 const int x = i + dx;21 const int y = j + dy;22 if (x < 0 || x == m || y < 0 || y == n)23 continue;24 if (x == m - 1 && y == n - 1)25 return step;26 if (grid[x][y] == 1 && eliminate == 0)27 continue;28 const int newEliminate = eliminate - grid[x][y];29 if (seen[x][y][newEliminate])30 continue;31 q.emplace(x, y, newEliminate);32 seen[x][y][newEliminate] = true;33 }34 }35 36 return -1;37 }38};39