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