<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:
        DP={}
        m=len(grid)
        n=len(grid[0])

        maxLen=0
        for i in range(m-1,-1,-1):
            for j in range(n-1,-1,-1):
                if grid[i][j]==1:
                    [b,l]=DP[(i,j)]=[
                        DP.get((i,j+1),[0,0])[0]+1,
                        DP.get((i+1,j),[0,0])[1]+1,
                    ]
                    minLen=min(l,b)
                    while minLen>0:
                        b2=DP.get((i+minLen-1,j),[0,0])[0]-DP.get((i+minLen-1,j+minLen-1),[0,0])[0]+grid[i+minLen-1][j+minLen-1]
                        l2=DP.get((i,j+minLen-1),[0,0])[1]-DP.get((i+minLen-1,j+minLen-1),[0,0])[1]+grid[i+minLen-1][j+minLen-1]
                        
                        if b2==l2 and b2==minLen:
                            # print(i,j,b2)
                            maxLen=max(maxLen,minLen)
                            break
                        minLen-=1
                # else:
                #     DP[(i,j)]=[0,0]
        # print(DP)
        return maxLen**2
        
18400