<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:
        m, n = len(grid), len(grid[0])
        sums = [[0 for _ in range(n)] for _ in range(m)]

        for i in range(m):
            for j in range(n):
                sum_at_loc = grid[i][j]
                if i > 0:
                    sum_at_loc += sums[i-1][j]
                if j > 0:
                    sum_at_loc += sums[i][j-1]
                if i > 0 and j > 0:
                    sum_at_loc -= sums[i-1][j-1]
                sums[i][j] = sum_at_loc

        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 0:
                    continue
                offset = min(i, j)
                while offset >= 0:
                    left = j - offset
                    top = i - offset
                    has_bottom_border = get_row_sum(sums, i, left, j) == offset+1
                    has_top_border = get_row_sum(sums, top, left, j) == offset+1
                    has_left_border = get_col_sum(sums, left, top, i) == offset+1
                    has_right_border =get_col_sum(sums, j, top, i) == offset+1

                    if all([has_bottom_border, has_top_border, has_left_border, has_right_border]): 
                        ans = max(ans, (offset+1)*(offset+1))
                        offset = -1
                    else:
                        offset -= 1
        
        return ans

# inclusive
def get_row_sum(sums, i, j_left, j_right):
    assert j_left <= j_right
    sum_to_right = sums[i][j_right] - (sums[i-1][j_right] if i > 0 else 0)
    if j_left > 0:
        sum_to_left = sums[i][j_left-1] - (sums[i-1][j_left-1] if i > 0 else 0)
    else:
        sum_to_left = 0
    return sum_to_right - sum_to_left

# inclusive
def get_col_sum(sums, j, i_top, i_bottom):
    assert i_top <= i_bottom
    sum_to_bottom = sums[i_bottom][j] - (sums[i_bottom][j-1] if j > 0 else 0)
    if i_top > 0:
        sum_to_top = sums[i_top-1][j] - (sums[i_top-1][j-1] if j > 0 else 0)
    else:
        sum_to_top = 0
    return sum_to_bottom - sum_to_top

17100