<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 {
    int row, col;
    void solve(vector<vector<int>>& grid, int r, int c, int& len) {
        int i = 1;
        for(; r + i < row && c + i < col; ++i) {
            if(grid[r][c + i] != 1 || grid[r + i][c] != 1)
                break;
        }
        --i; 
        
        while(i >= len) {
            bool pass = true;
            for(int j = 0; j <= i; ++j) {
                if(grid[r+i][c+j] != 1 || grid[r+j][c+i] != 1) {
                    pass = false;
                    break;
                }
            }
            if(pass) {
                len = i + 1;
                break;
            }
            --i;
        }
    }
public:
    int largest1BorderedSquare(vector<vector<int>>& grid) {
        int length = 0;
        row = grid.size(); col = grid[0].size();
        for(int i = 0; i < row; ++i) {
            for(int j = 0; j < col; ++j) {
                if(grid[i][j] == 1 && row - i > length && col - j > length) {
                    solve(grid, i, j, length);
                }
            }
        }
        return length * length;
    }
};
13500