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 Java from the credited upstream file 1293.java.
- 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 int shortestPath(int[][] grid, int k) {3 record T(int i, int j, int eliminate) {}4 final int m = grid.length;5 final int n = grid[0].length;6 if (m == 1 && n == 1)7 return 0;8 9 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};10 Queue<T> q = new ArrayDeque<>(List.of(new T(0, 0, k)));11 boolean[][][] seen = new boolean[m][n][k + 1];12 seen[0][0][k] = true;13 14 for (int step = 1; !q.isEmpty(); ++step)15 for (int sz = q.size(); sz > 0; --sz) {16 final int i = q.peek().i;17 final int j = q.peek().j;18 final int eliminate = q.poll().eliminate;19 for (int l = 0; l < 4; ++l) {20 final int x = i + DIRS[l][0];21 final int y = j + DIRS[l][1];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 final int newEliminate = eliminate - grid[x][y];29 if (seen[x][y][newEliminate])30 continue;31 q.offer(new T(x, y, newEliminate));32 seen[x][y][newEliminate] = true;33 }34 }35 36 return -1;37 }38}39