Maximal Rectangle

来源:互联网 发布:织梦cms使用手册 编辑:程序博客网 时间:2024/05/16 13:53

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;    }};


0 0
原创粉丝点击