Problems/208. Largest 1-Bordered Square

208. Largest 1-Bordered Square

MediumMatrix

Given an m x n binary grid where cells contain either 0 or 1, find the largest square subgrid whose boundary consists entirely of 1s. The interior cells of the square can be either 0 or 1. Return the total number of cells in this square (its area). If no such square exists, return 0.

Example 1
Input: grid = [ [1, 1, 1], [1, 0, 1], [1, 1, 1] ]
Output: 9
The entire 3x3 grid has a border of 1s, so the largest square area is 9.
Example 2
Input: grid = [ [1, 1, 0], [1, 1, 1], [1, 1, 1] ]
Output: 4
A 3x3 square is not possible because of the 0 at (0,2). The largest square is 2x2, spanning from (1,0) to (2,1), yielding an area of 4.
Example 3
Input: grid = [ [0] ]
Output: 0
No 1s exist in the grid, so the largest square area is 0.
Visualizer

Visualizer will appear here