Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// DO NOT write int main() function
int m = matrix.size();
if(m < 1) return 0;
int n = matrix[0].size();
vector<int> cache(m, 0);
int i,j,area, maxArea = 0,top;
stack<int> s;
for(i = n; i>= 0; i--)
{
for(int k = 0; k< m; k++)
if(matrix[k][i] == '1')
cache[k] ++ ;
else
cache[k] = 0;
for(j= 0; j< m; )
{
if(s.empty() || cache[j] >= cache[s.top()] )
{
s.push(j);
j++;
continue;
}else{
top = s.top();
s.pop();
area = cache[top] * ( s.empty() ? j : j - s.top() -1);
maxArea = maxArea > area ? maxArea : area ;
}
}
while(!s.empty())
{
top = s.top();
s.pop();
area = cache[top] * ( s.empty() ? j : j - s.top() -1);
maxArea = maxArea > area ? maxArea : area ;
}
}
return maxArea ;
}
};
--------------------------------------------------------------------天道酬勤!