22. Maximal Square
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example 1:

Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4Example 2:

Input: matrix = [["0","1"],["1","0"]]
Output: 1Example 3:
Input: matrix = [["0"]]
Output: 0Solution: (Bruteforce)
Algorithm: When we get a square with 1 We expand row, column 1 cell forward
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;
}
};Time Complexity: O(m * n) ^ 2
Solution: (DP)
Algorithm:
Time Complexity: O(m * n) Space Complexity: O(m+n)
Last updated
Was this helpful?