<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 tmp = 0;
        for (int i = 0; i != grid.size(); ++i)
        {
            tmp = 0;
            for (int j = 0; j != grid[0].size(); ++j)
            {
                if (grid[i][j] == 0)
                {
                    tmp = 0;
                }
                else
                {
                    ++tmp;
                }
                grid[i][j] = tmp;
            }
        }
        vector<vector<int>> prefixCol = grid;
        for (int j = 0; j != grid[0].size(); ++j)
        {
            tmp = 0;
            for (int i = 0; i != grid.size(); ++i)
            {
                if (prefixCol[i][j] == 0)
                {
                    tmp = 0;
                }
                else
                {
                    ++tmp;
                }
                prefixCol[i][j] = tmp;
            }
        }
        int left = min(grid.size(), grid[0].size());
        int answer = 0;
        bool find = false;        
        while (left)
        {
            find = false;
            for (int i = 0; i != grid.size(); ++i)
            {
                if (find) break;
                for (int j = 0; j != grid[0].size(); ++j)
                {
                    if (grid[i][j] >= left && (i + left - 1) < grid.size())
                    {
                        if (grid[i + left - 1][j] >= left)
                        {
                            if (prefixCol[i + left - 1][j] >= left)
                            {
                                if (prefixCol[i + left - 1][j - (left - 1)] >= left)
                                {
                                    find = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (find)
            {
                answer = max(answer, left*left);
                break;
            }
            --left;
        }
        return answer;
    }
};
14200