<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 rows = grid.size();
        int cols = grid[0].size();
        int maxSquareSize = 0;

        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                // Start looking for squares with size 1 and increase
                if (grid[x][y] == 1) {
                    for (int size = 1; size <= min(rows - x, cols - y); size++) {
                        // Check top and left sides
                        bool isValidSquare = true;
                        for (int k = 0; k < size; k++) {
                            if (grid[x + k][y] == 0 || grid[x][y + k] == 0) {
                                isValidSquare = false;
                                break;
                            }
                        }

                        // Check bottom and right sides
                        for (int k = 0; k < size; k++) {
                            if (grid[x + size - 1][y + k] == 0 || grid[x + k][y + size - 1] == 0) {
                                isValidSquare = false;
                                break;
                            }
                        }

                        if (isValidSquare) {
                            maxSquareSize = max(maxSquareSize, size);
                        }
                    }
                }
            }
        }

        return maxSquareSize * maxSquareSize;
    }
};

13400