Approach
Breadth-first search
For Smallest Rectangle Enclosing Black Pixels, 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 302.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 minArea(char[][] image, int x, int y) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = image.length;5 final int n = image[0].length;6 int[] topLeft = {x, y};7 int[] bottomRight = {x, y};8 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(x, y)));9 image[x][y] = '2'; 10 11 while (!q.isEmpty()) {12 final int i = q.peek().getKey();13 final int j = q.poll().getValue();14 for (int[] dir : DIRS) {15 final int r = i + dir[0];16 final int c = j + dir[1];17 if (r < 0 || r == m || c < 0 || c == n)18 continue;19 if (image[r][c] != '1')20 continue;21 topLeft[0] = Math.min(topLeft[0], r);22 topLeft[1] = Math.min(topLeft[1], c);23 bottomRight[0] = Math.max(bottomRight[0], r);24 bottomRight[1] = Math.max(bottomRight[1], c);25 q.offer(new Pair<>(r, c));26 image[r][c] = '2';27 }28 }29 30 final int width = bottomRight[1] - topLeft[1] + 1;31 final int height = bottomRight[0] - topLeft[0] + 1;32 return width * height;33 }34}35