Leetcode: 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.

Largest Rectangle in Histogram的进阶篇,计算柱状图最大矩形的解法可以进一步优化 - 不用两元组堆栈,用一个索引堆栈即可。关键是找到左右两侧比当前处理元素小的索引,面积为当前元素高度和左右索引差值的乘积。其他的就水到渠成了,把矩阵的每一行之上的所有元素看做一个柱状图。

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        int max_rect = 0;
        int rows = matrix.size();
        if (rows == 0) {
            return max_rect;
        }
        
        int cols = matrix[0].size();
        vector<int> sum(cols, 0);
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                if (matrix[i][j] == '0') {
                    sum[j] = 0;
                }
                else {
                    ++sum[j];
                }
            }
            max_rect = max(max_rect, largestRectangleArea(sum));
        }
        
        return max_rect;
    }
    
    int largestRectangleArea(vector<int> &height) {
        int max_area = 0;
        stack<int> indices;
        int top_index, area;
        int i = 0;
        while (i < height.size()) {
            if (indices.empty() || height[indices.top()] <= height[i]) {
                indices.push(i++);
            }
            else {
                top_index = indices.top();
                indices.pop();
                area = height[top_index] * (indices.empty() ? i : i - indices.top() - 1);
                max_area = max(max_area, area);
            }
        }
        
        while (!indices.empty()) {
            top_index = indices.top();
            indices.pop();
            area = height[top_index] * (indices.empty() ? i : i - indices.top() - 1);
            max_area = max(max_area, area);
        }
        
        return max_area;
    }
};


你可能感兴趣的:(LeetCode)