<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 {
public:
    int largest1BorderedSquare(vector<vector<int>>& grid) {
        int n = grid.size();
        int m = grid[0].size();
        
        // Resize mat to the same size as grid, initializing each element with (0,0)
        vector<vector<pair<int, int>>> mat(n, vector<pair<int, int>>(m, {0, 0}));
        
        for(int i = 0; i < n; i++) {
            int cntx = 0;
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 0) {
                    mat[i][j] = {0, 0};
                    cntx = 0;
                } else {
                    cntx++;
                    if(i - 1 >= 0) {
                        int y = mat[i - 1][j].first;
                        mat[i][j] = {y + 1, cntx};
                    } else {
                        mat[i][j] = {1, cntx};
                    }
                }
            }
        }
        
        int maxi = 0;
        for(int i = n - 1; i >= 0; i--) {
            for(int j = m - 1; j >= 0; j--) {
                int sml = min(mat[i][j].first, mat[i][j].second);
                while(sml > 0) {
                    if(i - sml + 1 >= 0 && j - sml + 1 >= 0 && 
                       mat[i - sml + 1][j].second >= sml && mat[i][j - sml + 1].first >= sml) {
                        maxi = max(maxi, sml * sml);
                        break; // No need to check smaller squares for this point
                    }
                    sml--;
                }
            }
        }
        return maxi;
    }
};

14500