# 221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

For example, given the following matrix:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0


Return 4.

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <stack>
using namespace std;
int maximalSquarehelper(vector<int>& dp,int d)
{
int max = 0;
stack<int> stk;
dp.push_back(0);
for (int i = 0; i < dp.size(); i++)
{
if (stk.empty() || dp[i] >= dp[stk.top()])stk.push(i);
else
{
int peek = stk.top();
stk.pop();
int temp = stk.empty() ? (dp[peek] < i ? dp[peek] * dp[peek] : i * i) : (dp[peek] < (i - 1 - stk.top()) ? dp[peek] * dp[peek] : (i - 1 - stk.top()) * (i - 1 - stk.top()));
max = max > temp ? max : temp;
i--;
}
}
dp.pop_back();
return max;
}
int maximalSquare(vector<vector<char>>& matrix)
{
int rows = matrix.size();
if (rows == 0)return 0;
int cols = matrix[0].size();
if (cols == 0)return 0;
vector<int> dp(cols, 0);
int max = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if (matrix[i][j] == '0')dp[j] = 0;
else dp[j]++;
}
int temp = maximalSquarehelper(dp, i);
max = max > temp ? max : temp;
}
return max;
}
int main()
{
vector<vector<char>> matrix{
{'1','0','1','0','0','1','1','1','0'},
{'1','1','1','0','0','0','0','0','1'},
{'0','0','1','1','0','0','0','1','1'},
{'0','1','1','0','0','1','0','0','1'},
{'1','1','0','1','1','0','0','1','0'},
{'0','1','1','1','1','1','1','0','1'},
{'1','0','1','1','1','0','0','1','0'},
{'1','1','1','0','1','0','0','0','1'},
{'0','1','1','1','1','0','0','1','0'},
{'1','0','0','1','1','1','0','0','0'} };
cout << maximalSquare(matrix) << endl;
system("pause");
return 0;
}