<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 n = grid.size();
        if (n == 0) return 0;
        int m = grid[0].size();
        int maxSize = 0;

        // Initialize auxiliary matrices
        vector<vector<int>> left(n, vector<int>(m, 0));
        vector<vector<int>> up(n, vector<int>(m, 0));

        // Preprocess the grid and compute left and up matrices
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (grid[i][j] == 1) {
                    left[i][j] = (j > 0) ? left[i][j - 1] + 1 : 1;
                    up[i][j] = (i > 0) ? up[i - 1][j] + 1 : 1;
                } else {
                    left[i][j] = up[i][j] = 0;
                }
            }
        }

        // Iterate over possible square sizes from largest to smallest
        for (int size = min(n, m); size > 0; --size) {
            bool found = false;
            // Check all possible positions for a square of this size
            for (int i = 0; i <= n - size; ++i) {
                for (int j = 0; j <= m - size; ++j) {
                    int x = i + size - 1;
                    int y = j + size - 1;

                    // Check if the borders have enough ones
                    if (up[x][j] >= size && up[x][y] >= size &&
                        left[i][y] >= size && left[x][y] >= size) {
                        maxSize = size;
                        found = true;
                        break; // Found the largest possible square for this size
                    }
                }
                if (found) break;
            }
            if (found) break; // No need to check smaller sizes
        }

        return maxSize * maxSize; // Return the area of the largest square
    }
};


14600