Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
思路:
用A[i][j]表示从i,j向上有多少个连续的1,之后可以转换成Largest Rectangle in Histogram
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if(matrix.empty() || matrix[0].empty())
return 0;
n = matrix.size();
m = matrix[0].size();
vector<vector<int> > A = calc_new_matrix(matrix);
maxx = 0;
for(int i = 0; i < n; ++i){
stack<int> S;
for(int j = 0; j < m + 1; ++j){
if(S.empty()){
S.push(j);
}
else{
while(!S.empty() && A[i][S.top()] >= A[i][j]){
int h = S.top();
S.pop();
if(S.empty()){
maxx = max(maxx, A[i][h] * j);
}
else{
maxx = max(maxx, A[i][h] * (j - 1 - S.top()));
}
}
S.push(j);
}
}
}
return maxx;
}
private:
int n, m, maxx;
vector<vector<int> > calc_new_matrix(vector<vector<char> > &matrix){
vector<vector<int> > A(n);
for(auto &v:A){
v = vector<int> (m + 1);
}
for(int i = 0; i < m; ++i){
A[0][i] = (matrix[0][i] == '1')? 1 : 0;
}
for(int i = 1; i < n; ++i)
for(int j = 0; j < m; ++j){
A[i][j] = (matrix[i][j] == '1')? A[i - 1][j] + 1 : 0;
}
for(int i = 0; i < n; ++i){
A[i][m] = -1;
}
return A;
}
};