[Leetcode] Maximal Rectangle Maximum Rectangle

Source: Internet
Author: User

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

This is the previous largest Rectangle in histogram histogram of the largest rectangular extension, the two-dimensional matrix of the problem can be viewed as a histogram, the input matrix has how many rows, you can form a number of histograms, each histogram is called largest The maximum rectangular area can be obtained by means of the largest rectangle in the Rectangle in histogram histogram. So the only thing to do is to make each layer of the histogram, because the topic limit the input matrix characters only ' 0 ' and ' 1 ' two, so processing is relatively simple. The method is, for each point, if it is ' 0 ', then 0, if it is ' 1 ', will be assigned the height of the previous value plus 1. See the code below for details:

classSolution { Public:    intMaximalrectangle (vector<vector<Char> > &matrix) {        intres =0; Vector<int>height;  for(inti =0; I < matrix.size (); ++i) {height.resize (Matrix[i].size ());  for(intj =0; J < Matrix[i].size (); ++j) {Height[j]= Matrix[i][j] = ='0'?0: (1+Height[j]); } Res=Max (res, largestrectanglearea (height)); }        returnRes; }    intLargestrectanglearea (vector<int> &height) {        intres =0; Stack<int>s; Height.push_back (0);  for(inti =0; I < height.size (); ++i) {if(S.empty () | | height[s.top ()] <=Height[i]) s.push (i); Else {                intTMP =S.top ();                S.pop (); Res= Max (res, height[tmp] * (S.empty ()? I: (I-s.top ()-1))); --i; }        }        returnRes; }};

[Leetcode] Maximal Rectangle Maximum 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.