22. Maximal Square
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4Input: matrix = [["0","1"],["1","0"]]
Output: 1Input: matrix = [["0"]]
Output: 0Solution: (Bruteforce)
class Solution
{
public:
int maximalSquare(vector<vector<char>> &matrix)
{
int n = matrix.size();
int m = matrix[0].size();
int maxSquare = 0;
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[0].size(); j++)
{
if (matrix[i][j] == '1')
{
bool isSquare = true;
int x = i;
int y = j;
while (isSquare && x < n && y < m)
{
for (int p = i; p <= x; p++)
{
for (int q = j; q <= y; q++)
{
if (matrix[p][q] == '0')
{
isSquare = false;
break;
}
}
if (!isSquare)
{
break;
}
}
if (isSquare)
{
int square = (x - i) + 1;
if (square > maxSquare)
{
maxSquare = square;
}
x++;
y++;
}
}
}
}
}
return maxSquare * maxSquare;
}
};Solution: (DP)
Last updated

