Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example:
Input: [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ] Output: 6题源: here;完整实现: here
思路:
这道题可以转换为求解直方图中的最大矩阵(即第84题)来解决,我们将按行将原矩阵投影为直方图,然后记录每一行所对应的直方图的最大矩阵。代码如下:
int largestRectangleArea(vector<int>& heights){
stack<int> records; int maxRec = 0;
heights.push_back(0);
for (int i = 0; i < heights.size(); i++){
if (records.size() == 0 || heights[records.top()] <= heights[i]){
records.push(i); continue;
}
int top = records.top(); records.pop();
int rec = records.size() ? (i - records.top() - 1)*heights[top] : i*heights[top];
maxRec = max(maxRec, rec);
i--;
}
return maxRec;
}
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.size() == 0) return 0;
vector<int> heights(matrix[0].size(), 0);
int maxRec = 0;
for (int i = 0; i < matrix.size(); i++){
for (int j = 0; j < matrix[0].size(); j++){
if (matrix[i][j] == '1'){
heights[j] += 1;
}
else heights[j] = 0;
}
int rec = largestRectangleArea(heights);
maxRec = max(maxRec, rec);
}
return maxRec;
}