[LeetCode]Maximal Rectangle

来源:互联网 发布:mill9.1编程文字教程 编辑:程序博客网 时间:2024/05/18 03:00

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

在一个M * N的矩阵中,所有的元素只有0和1, 找出只包含1的最大矩形。

例如:图中是一个4 × 6的矩形,画出红色的是我们要找到的区域。

仔细观察发现:因为我们要找的是矩形,所以它一定是以 某个行元素开始的,这样的话,其实我们要找到的某个矩形就转换成 一某一个行开始的 histogram的最大矩形问题了。

那么我们原始矩形可以变成如下的形式的数据:


第一行表示,我们以第一行作为底边,所形成的 histogram的高度,其他行也类似。所以问题变成了 枚举每一行,然后求出每一行对应的histogram的最大矩形。histogram参考:

class Solution {public:    int maximalRectangle(vector<vector<char>>& matrix) {        int col = matrix.size();        if(col==0)            return 0;        int row = matrix[0].size();        int res = 0;        for(int j=0; j<row; ++j){            int flag = 0;            for(int i=0; i<col; ++i){                if(matrix[i][j]=='1'){                    flag++;                    matrix[i][j]='0'+flag;                }                else if(matrix[i][j]=='0'){                    flag = 0;                }            }        }        for(int i=0; i<col; ++i){            int temp = largestRectangleArea(matrix[i]);            res = res>temp?res:temp;        }        return res;    }    int largestRectangleArea(vector<char>& height) {       stack<int> index;       stack<char> h;       if(height.size()==0)            return 0;       index.push(0);       h.push(height[0]);       int area = 0;       for(int i=1; i<height.size(); ++i){           if(h.empty()||height[i]>h.top()){               index.push(i);               h.push(height[i]);           }           else if(height[i]<h.top()){               int tempIdx = 0;               while(!h.empty() && height[i]<=h.top()){                  tempIdx = index.top();                  area = area>(i-index.top())*(h.top()-'0')?area:(i-index.top())*(h.top()-'0');                  h.pop();                  index.pop();               }               index.push(tempIdx);               h.push(height[i]);           }       }       while(!h.empty()){           area = area >(height.size()-index.top())*(h.top()-'0')? area:(height.size()-index.top())*(h.top()-'0');           h.pop();           index.pop();       }       return area;    }};


0 0
原创粉丝点击