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
- 36 lines of C++ from the credited upstream file 302.cpp.
- 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:3 int minArea(vector<vector<char>>& image, int x, int y) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 const int m = image.size();6 const int n = image[0].size();7 vector<int> topLeft{x, y};8 vector<int> bottomRight{x, y};9 queue<pair<int, int>> q{{{x, y}}};10 image[x][y] = '2'; 11 12 while (!q.empty()) {13 const auto [i, j] = q.front();14 q.pop();15 for (const auto& [dx, dy] : kDirs) {16 const int r = i + dx;17 const int c = j + dy;18 if (r < 0 || r == m || c < 0 || c == n)19 continue;20 if (image[r][c] != '1')21 continue;22 topLeft[0] = min(topLeft[0], r);23 topLeft[1] = min(topLeft[1], c);24 bottomRight[0] = max(bottomRight[0], r);25 bottomRight[1] = max(bottomRight[1], c);26 q.emplace(r, c);27 image[r][c] = '2';28 }29 }30 31 const int width = bottomRight[1] - topLeft[1] + 1;32 const int height = bottomRight[0] - topLeft[0] + 1;33 return width * height;34 }35};36