<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 dp[100][100][4] = { 0 };
    int direction[5] = { 0, 1, 0, -1, 0 };
    int largest1BorderedSquare(vector<vector<int>>& grid) {
        int maxLen = 0, m = grid.size(), n = grid[0].size();
        for (int row = 0; row < m; row++) {
            for (int col = 0; col < n; col++) {
                if (!grid[row][col])
                    continue;
                for (int len = 0; len + row < m && len + col < n; len++) {
                    int upper = borderLength(grid, row, col, 0);
                    int left = borderLength(grid, row, col, 1);
                    int down = borderLength(grid, row + len, col + len, 2);
                    int right = borderLength(grid, row + len, col + len, 3);
                    if (min({upper, left, down, right}) >= len+1)
                        maxLen = max(maxLen, len + 1);
                }
            }
        }
        return maxLen * maxLen;
    }

    int borderLength(vector<vector<int>>& grid, int row, int col, int dir) {
        if (row < 0 || row == grid.size() || col < 0 || col == grid[0].size() || grid[row][col] == 0)
            return 0;

        if (dp[row][col][dir])
            return dp[row][col][dir];

        dp[row][col][dir] = 1 + borderLength(grid, row + direction[dir], col + direction[dir+1], dir);
        return dp[row][col][dir];
    }
};
13700