给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
思路一:遍历每行,如果该行当前值为0,则赋值0,否则统计当前值所处列往上的1的个数,每行统计完毕,利用求矩形最大面积的方法求出可构成的最大值,最后结果返回每行之间的最大值即可。
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if(matrix.empty())
return 0;
int row = matrix.size();
int col = matrix[0].size();
vector<char> rect(col,0);
int maxval = INT_MIN;
for(int i=0;i<row;++i){
for(int j=0;j<col;++j){
rect[j] = (matrix[i][j]=='0')?0:rect[j]+1;
}
maxval = max(maxval,getMaxRect(0,col-1,rect));
}
return maxval;
}
int getMaxRect(int left, int right, vector<char>& rect){
if(left>right)
return 0;
int minIndex = left;
bool increase = true;
for(int i=left+1;i<=right;++i){
if(rect[i-1]>rect[i])
increase = false;
if(rect[i]<rect[minIndex])
minIndex = i;
}
if(increase){
int maxval = INT_MIN;
for(int i=left;i<=right;++i)
maxval = max(maxval,rect[i]*(right-i+1));
return maxval;
}
return max(rect[minIndex]*(right-left+1),max(getMaxRect(left,minIndex-1,rect),getMaxRect(minIndex+1,right,rect)));
}
};
思路二:全动态规划,待补