Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.
Example 1:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 9
Example 2:
Input: grid = [[1,1,0,0]]
Output: 1
Constraints:
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j] is 0 or 1
Solutions
Solution 1: Prefix Sum + Enumeration
Thinking
Checking four sides of every \(k\times k\) square by walking them multiplies the cubic enumeration by \(k\). After storing, for each cell, the run of \(1\)s down and right, each side is an \(O(1)\) length test.
Enumerate \(k\) from large to small and the top-left corner; the first success is the maximum area.
We can use the prefix sum method to preprocess the number of consecutive 1s down and to the right of each position, denoted as down[i][j] and right[i][j].
Then we enumerate the side length \(k\) of the square, starting from the largest side length. Then we enumerate the upper left corner position \((i, j)\) of the square. If it meets the condition, we can return \(k^2\).
The time complexity is \(O(m \times n \times \min(m, n))\), and the space complexity is \(O(m \times n)\). Here, \(m\) and \(n\) are the number of rows and columns of the grid, respectively.