Original title Address
Specifying any row as the lower boundary of the rectangle, the problem becomes the rectangle that asks for the maximum area of the histogram, see previous article.
So the idea is, from top to bottom, in order to find the histogram of the maximum area of the rectangle, feeling instantaneous no difficulty. In the following code, the first function is moved in intact.
Time complexity is O (n^2)
Code:
1 intLargestrectanglearea (vector<int> &height) {2 intMaxarea =0;3 intn =height.size ();4stack<int>St;5 inth, W;6 7 for(inti =0; I < n; i++) {8 if(St.empty () | | height[st.top ()] <Height[i])9 St.push (i);Ten Else { One while(!st.empty () && height[st.top ()] >Height[i]) { Ah =height[st.top ()]; - St.pop (); -W = St.empty ()? I:i-(St.top () +1); theMaxarea = Max (Maxarea, H *W); - } - St.push (i); - } + } - + while(!St.empty ()) { Ah =height[st.top ()]; at St.pop (); -W = St.empty ()? -N-(st.top () +1); -Maxarea = Max (Maxarea, H *W); - } - - returnMaxarea; in } - to intMaximalrectangle (vector<vector<Char> > &matrix) { + if(Matrix.empty () | | matrix[0].empty ()) - return 0; the * intMaxarea =0; $ inth =matrix.size ();Panax Notoginseng intW = matrix[0].size (); -vector<int> Histo (w,0); the + for(inti =0; I < H; i++) { A //Calculate Histogram the for(intj =0; J < W; J + +) +HISTO[J] = (Histo[j] +1) * (Matrix[i][j]-'0'); - $Maxarea =Max (Maxarea, Largestrectanglearea (Histo)); $ } - - returnMaxarea; the}
Leetcode#85 Maximal Rectangle