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.
Function Signature
def largest_1_bordered_square(grid: list[list[int]]) -> int:
Rules
-
grid
is a list of rows, and every row has the same length. The grid does not have to be square.
-
A square subgrid of side
s
covers
s
consecutive rows and
s
consecutive columns. Its border is its first row, last row, first column and last column. Interior cells may be
0
or
1
.
-
A single cell holding
1
is a valid square of side 1.
-
Return
s * s
for the largest valid side
s
, or
0
when the grid contains no
1
.
Constraints
-
1 <= len(grid) <= 100
-
1 <= len(grid[0]) <= 100
-
grid[i][j]
is
0
or
1
Examples
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 9
The whole 3x3 grid is a square whose border cells are all 1. The 0 in the middle is an interior cell, so it does not matter.
Input: grid = [[1,1,0,0]]
Output: 1
With a single row, the largest possible square has side 1, and any cell holding 1 qualifies.
Input: grid = [[1,0,1],[1,1,1],[1,1,1]]
Output: 4
The full 3x3 square fails because its top row contains a 0. The 2x2 square at rows 1-2 and columns 1-2 has all 1s on its border, so the answer is 4.