[Problem]
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
[Solution]
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
// get the size of the maximal rectangle
int maximalRectangle(int height[], int len){
if(len == 0)return 0;
// set the leftH
int leftH[len];
for(int i = 0; i < len; ++i){
if(i == 0 || height[i] > height[i-1]){
leftH[i] = i;
}
else{
int j = leftH[i-1];
while(true){
if(j != leftH[j]){
j = leftH[j];
}
else if(j > 0 && height[j-1] >= height[i]){
j--;
}
else{
break;
}
}
leftH[i] = j;
}
}
// set the rightH
int rightH[len];
for(int i = len-1; i >= 0; --i){
if(i == len-1 || height[i] > height[i+1]){
rightH[i] = i;
}
else{
int j = rightH[i+1];
while(true){
if(j != rightH[j]){
j = rightH[j];
}
else if(j < len-1 && height[j+1] >= height[i]){
j++;
}
else{
break;
}
}
rightH[i] = j;
}
}
// get the maximal rectangle
int res = 0, area = 0;
for(int i = 0; i < len; ++i){
area = height[i] * (rightH[i] - leftH[i] + 1);
res = max(res, area);
}
return res;
}
// get the maximal rectangle in the matrix
int maximalRectangle(vector<vector<char> > &matrix) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// empty matrix
if(matrix.size() == 0 || matrix[0].size() == 0)return 0;
// init height
int **height = new int*[matrix.size()];
for(int i = 0; i < matrix.size(); ++i){
height[i] = new int[matrix[i].size()];
for(int j = 0; j < matrix[i].size(); ++j){
// the height is 0
if(matrix[i][j] == '0'){
height[i][j] = 0;
}
else{
// the height is the previous row's height +1
if(i > 0){
height[i][j] = height[i-1][j] + 1;
}
else{
height[i][j] = 1;
}
}
}
}
// get result
int res = 0;
for(int i = 0; i < matrix.size(); ++i){
res = max(res, maximalRectangle(height[i], matrix[i].size()));
}
return res;
}
};