Problem Description
Given a 2D grid of 0s and 1s, find the largest square subgrid such that every cell on its border is 1. Return the number of elements in that square (i.e. side_length^2), or 0 if no such subgrid exists.
Key Insights
- A valid square exists if its entire border (top, bottom, left, right) is filled with 1s.
- Precompute the number of consecutive 1s to the left and above each cell.
- Use dynamic programming to quickly check if a border segment of a candidate square is entirely 1s.
- Iterate from the larger possible square size downwards to return early upon discovering the maximal square.
Space and Time Complexity
Time Complexity: O(n * m * min(n, m)) where n and m are the dimensions of the grid. Space Complexity: O(n * m) for the auxiliary left and up matrices.
Solution
We precompute two DP matrices:
- One (left) that counts the number of consecutive 1s to the left of and including the current cell.
- Another (up) that counts the consecutive 1s upwards. For every cell considered as the bottom-right corner of a potential square, the maximum possible side length is limited by the minimum value from these matrices at that cell. We then check if the corresponding top border and left border meet the requirement using the DP matrices. By iterating downward from the maximum possible size, we can update the largest found valid square, ensuring that we return its area immediately once identified.