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.

class Solution {
public:
    int visit(vector<int> &height)
    {
        height.push_back(0);

        if (height.empty())
        {
            return 0;
        }
        int size = height.size();
        stack<int> s;
        int result = 0;
        for (int i = 0; i < size;)
        {
            if (s.empty() || height[i] > height[s.top()])
            {
                s.push(i);
                i++;
            }
            else
            {
                int temp = height[s.top()];
                s.pop();
                if (s.empty())
                {
                    result = max(result, i*temp);
                }
                else
                {
                    result = max(result, (i-s.top()-1)*temp);
                }
            }
        }

        return result;
    }

    int maximalRectangle(vector<vector<char>>& matrix) {
        if (matrix.empty())
        {
            return 0;
        }
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> height(n+1, 0);
        int result = 0;
        int cur = 0;
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (matrix[i][j] == '0')
                {
                    height[j] = 0;
                }
                else
                {
                    height[j] += 1;
                }
            }
            cur = visit(height);
            result = max(cur, result);
        }

        return result;
    }
};


你可能感兴趣的:(Maximal Rectangle)