<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 largest1BorderedSquare(vector<vector<int>>& grid) {
    int res = 0;
    int m = grid.size();
    int n = grid[0].size();
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (!grid[i][j]) continue;
            int curMaxSize = min(m - i, n - j);
            for (int curI = i; curI < i + curMaxSize; curI++) {
                if (!grid[curI][j]) {
                    curMaxSize = curI - i;
                    break;
                }
            }
            for (int curJ = j; curJ < j + curMaxSize; curJ++) {
                if (!grid[i][curJ]) {
                    curMaxSize = curJ - j;
                    break;
                }
            }
            for (int a = curMaxSize; a > res; a--) {
                int maxI = i + a - 1;
                int maxJ = j + a - 1;
                bool valid = true;
                for (int curI = i; valid && curI <= maxI; curI++) {
                    if (!grid[curI][maxJ]) {
                        valid = false;
                    }
                }
                for (int curJ = j; valid && curJ <= maxJ; curJ++) {
                    if (!grid[maxI][curJ]) {
                        valid = false;
                    }
                }
                if (valid) res = a;
            }
        }
    }
    return res * res;
    }
};
13300