地址:http://oj.leetcode.com/problems/maximal-rectangle/
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
申请一个同给定矩阵matrix同样大小的矩阵dp,先对矩阵的每一行做预处理,每一行的第一列如果矩阵中是’1‘,dp[row][0]赋值为1.第一列之后若matrix[row][j] == ’1‘,dp[row][j] += dp[row][j-1], 否则dp[row][j] = 0 表示matrix在row行此列及其之前的列连续是’1‘个数。这相当于是之后要求的最大矩阵的宽度。
长度在遍历中确定。长度从0开始向上递增,每次递增都要重新计算宽度(取最小)。
另外要注意的是题目的意思是[['1']]这样的是返回1,[['1', '1']['1', '1']]返回4,其实就是最大矩形中’1‘个数,而不是题目里的“area”意思。不知道是不是笔者理解的有问题。
参考代码:
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if(matrix.empty())
return 0;
int row = matrix.size();
int col = matrix[0].size();
vector<vector<int>>dp;
for(int i = 0; i<row; ++i)
{
vector<int>vec(col, 0);
dp.push_back(vec);
for(int j=0; j<col; ++j)
{
if(j==0)
dp[i][j] = matrix[i][j]=='1' ? 1 : 0;
else
dp[i][j] = matrix[i][j]=='1' ? dp[i][j-1] + 1 : 0;
}
}
int ans = 0;
for(int i=0; i<row; ++i)
{
for(int j=0; j<col; ++j)
{
int width = dp[i][j];
if(width>0)
{
for(int cnt = i; cnt>=0 && width>0; --cnt)
{
width = min(width, dp[cnt][j]);
ans = max(ans, width*(i-cnt+1));
}
}
}
}
return ans;
}
};