"Leetcode" maximal Rectangle

Source: Internet
Author: User

Maximal Rectangle

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

If you use DP to determine whether the (BEGIN1,END1) ~ (BEGIN2,END2) range is 1, it will time out.

For matrix matrices, build the height array row by line, calling largest Rectangle in histogram.

Build the height array method on the matrix I Line: for Height[j], that is, starting from matrix[i][j], up to 1 consecutive numbers of matrix[0][j].

classSolution { Public:    intMaximalrectangle (vector<vector<Char> > &matrix) {        if(Matrix.empty ())return 0; intresult =0; introw =matrix.size (); intCol = matrix[0].size ();  for(inti =0; i < row; i + +)        {//for ith vector, reduct to "largest Rectangle in histogram"vector<int> Height (col,0);  for(intj =0; J < Col; J + +)            {                intIND =i;  while(Ind >=0&& Matrix[ind][j] = ='1') {IND--; HEIGHT[J]++; }} result=max (result, Largestrectanglearea (height)); }        returnresult; }        intLargestrectanglearea (vector<int> &height) {        if(Height.empty ())return 0; intresult =0; Stack<int> s;//elements in stack S is kept in ascending order        intIND =0;  while(Ind <height.size ()) {            if(S.empty () | | height[ind]>=S.top ())            {S.push (height[ind]); }            Else            {                intCount =0;//Pop Count                 while(!s.empty () && height[ind]<S.top ()) {                    inttop =S.top ();                    S.pop (); Count++; Result= Max (result, count*top); }                 for(inti =0; I <= count; i + +) S.push (Height[ind]); //Push count+1 times} IND++; }        //All elements is in the stack s, and in ascending order        intCount =0;  while(!S.empty ()) {Count++; inttop =S.top ();            S.pop (); Result= Max (result, count*top); }                returnresult; }};

"Leetcode" maximal Rectangle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.