<p>Given a 2D <code>grid</code> of <code>0</code>s and <code>1</code>s, return the number of elements in&nbsp;the largest <strong>square</strong>&nbsp;subgrid that has all <code>1</code>s on its <strong>border</strong>, or <code>0</code> if such a subgrid&nbsp;doesn&#39;t exist in the <code>grid</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1,1],[1,0,1],[1,1,1]]
<strong>Output:</strong> 9
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> grid = [[1,1,0,0]]
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= grid.length &lt;= 100</code></li>
	<li><code>1 &lt;= grid[0].length &lt;= 100</code></li>
	<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code></li>
</ul>
class Solution:
    def largest1BorderedSquare(self, grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])

        visited = set()

        def getSize(x, y):
            nonlocal cols, rows
            
            visited.add((x,y))
            
            h = 0
            _y = y
            while _y < rows and grid[_y][x] == 1:
                h += 1
                _y += 1

            w = 0
            _x = x
            while _x < cols and grid[y][_x] == 1:
                w += 1
                _x += 1

            maxSize = min(w, h)

            #validate
            while maxSize > 1:
                if grid[y + maxSize - 1][x + maxSize - 1] != 1:
                    maxSize -= 1
                    continue

                _x = x + maxSize - 2
                while _x > x and grid[y + maxSize - 1][_x] == 1:
                    _x -= 1

                if _x > x:
                    maxSize -= 1
                    continue
                    
                _y = y + maxSize - 2
                while _y > y and grid[_y][x + maxSize - 1] == 1:
                    _y -= 1

                if _y > y:
                    maxSize -= 1
                    continue
                
                break

            return maxSize * maxSize

        m = 0
        for y in range(rows):
            for x in range(cols):
                if (x, y) in visited:
                    continue

                if grid[y][x] == 0:
                    continue

                size = getSize(x, y)
                m = max(m, size)

        return m
17900