LeetCode——maximal-rectangle

Question

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

Solution

这个题目可以借鉴LeetCode——largest-rectangle-in-histogram 的思路,求最大矩阵的面积,所以我们只需要按行把给定’0’,‘1’矩阵,转换成对应的高度即可,然后计算最大矩阵面积。

Code

时间复杂度O(n^2).

class Solution {
public:
    int maximalRectangle(vector<vector<char> > &matrix) {
        int row = matrix.size();
        if (row <= 0)
            return 0;
        int col = matrix[0].size();
        vector<vector<int>> heights;
        for (int i = 0; i < row; i++) {
            vector<int> tmp;
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] != '0') {
                    // 累加高度
                    if (i - 1 >= 0 && matrix[i - 1][j] != '0')
                        matrix[i][j] += (matrix[i - 1][j] - '0');
                    tmp.push_back(matrix[i][j] - '0');
                } else {
                	// 被‘0’断开了,就需要计算一次
                    if (tmp.size() > 0) {
                        heights.push_back(tmp);
                        tmp.clear();
                    }
                }
            }
            if (tmp.size() > 0)
            	heights.push_back(tmp);
        }
        int res = 0;
        for (int i = 0; i < heights.size(); i++) {
            res = max(res, calc(heights[i]));
        }
        return res;
    }
    // 给定高度,求最大矩阵面积,时间复杂度O(n)
    int calc(vector<int>& height) {
        if (height.size() <= 0)
            return 0;
        stack<int> tb;
        int n = height.size();
        int res = 0;
        for (int i = 0; i < n; i++) {
            while (!tb.empty() && height[tb.top()] >= height[i]) {
                int index = tb.top();
                tb.pop();
                if (tb.empty()) {
                    res = max(res, i * height[index]);
                } else {
                    res = max(res, (i - tb.top() - 1) * height[index]);
                }
            }
            tb.push(i);
        }
        while (!tb.empty()) {
            int index = tb.top();
            tb.pop();
            if (tb.empty()) {
                res = max(res, n * height[index]);
            } else {
                res = max(res, (n - tb.top() - 1) * height[index]);
            }
        }
        return res;
    }
};
posted @ 2017-10-31 11:46  清水汪汪  阅读(191)  评论(0编辑  收藏  举报