1. 题目
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
2. 思路
将m*n的矩阵,转换成为m个数组,既可以用上一题的方法求解。【leetcode】84. Largest Rectangle in Histogram 最大面积的覆盖矩阵
参考了http://blog.csdn.net/doc_sgl/…
3. 代码
耗时:19ms
class Solution {
public:
// 对m*n的矩阵,转化为m个84题的一维数组的最大矩形问题。
// 转化方法是,对当前行转换为当前位置的上方连续1的个数作为一个高度值
int maximalRectangle(vector<vector<char>>& matrix) {
vector<vector<int>> matrix2;
int m = matrix.size();
if (m == 0) { return 0; }
int n = matrix[0].size();
if (n == 0) {return 0; }
for (int i = 0; i < m; i++) {
vector<int> row;
for (int j = 0; j < n; j++) {
row.push_back(matrix[i][j] == '0' ? 0 : 1);
}
matrix2.push_back(row);
}
return maximalRectangle(matrix2);
}
int maximalRectangle(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) { return 0; }
int n = matrix[0].size();
if (n == 0) {return 0; }
int max_area = largestRectangleArea(matrix[0]);
for (int i = 1; i < m; i++) {
vector<int>& line_up = matrix[i-1];
vector<int>& line = matrix[i];
for (int j = 0; j < n; j++) {
if (line[j] == 1) { line[j] = line_up[j] + 1; }
}
int area = largestRectangleArea(line);
//cout << "i=" << i << " area=" << area << endl;
if (area > max_area) { max_area = area; }
}
return max_area;
}
int largestRectangleArea(vector<int>& heights) {
int max_area = 0;
heights.push_back(0);
int sz = heights.size();
int stack[sz];
stack[0] = heights[0];
int stack_idx = 0;
int i = 1;
while (stack_idx >= 0 && i < sz) {
if (heights[i] >= stack[stack_idx]) {
stack[++stack_idx] = heights[i++];
continue;
}
while (stack_idx >= 0 && stack[stack_idx] > heights[i]) {
int area = stack[stack_idx] * (i - stack_idx);
if (area > max_area) { max_area = area; }
stack_idx--;
}
while (stack_idx < i) {
stack[++stack_idx] = heights[i];
}
i++;
}
return max_area;
}
};