Approach
Breadth-first search
For Minimum Obstacle Removal to Reach Corner, 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
- 35 lines of Java from the credited upstream file 2290.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 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 minimumObstacles(int[][] grid) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = grid.length;5 final int n = grid[0].length;6 Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) {7 { offer(new int[] {grid[0][0], 0, 0}); } 8 };9 int[][] dist = new int[m][n];10 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));11 dist[0][0] = grid[0][0];12 13 while (!minHeap.isEmpty()) {14 final int d = minHeap.peek()[0];15 final int i = minHeap.peek()[1];16 final int j = minHeap.poll()[2];17 if (i == m - 1 && j == n - 1)18 return d;19 for (int[] dir : DIRS) {20 final int x = i + dir[0];21 final int y = j + dir[1];22 if (x < 0 || x == m || y < 0 || y == n)23 continue;24 final int newDist = d + grid[i][j];25 if (newDist < dist[x][y]) {26 dist[x][y] = newDist;27 minHeap.offer(new int[] {newDist, x, y});28 }29 }30 }31 32 return dist[m - 1][n - 1];33 }34}35