1 classSolution {2 Public:3 intMaximalrectangle (vector<vector<Char>>&matrix) {4 /** Largest Rectangle based solution **/5 if(Matrix.size () <=0|| matrix[0].size () <=0)6 return 0;7 intm=matrix.size ();8 intn=matrix[0].size () +1;9 intH=0, w=0, result=0;Tenvector<int> Height (n,0); One for(intI=0; i<m; i++){ Astack<int>s; - for(intj=0; j<n; J + +){ - /** Update the current row ended height array **/ the if(j<n-1){ - if(matrix[i][j]=='1') height[j]+=1; - Elseheight[j]=0; - } + /** Use the histogram-max-rectangle-module **/ - while(!s.empty () && height[s.top ()]>=Height[j]) { +H=height[s.top ()]; A S.pop (); atW=s.empty ()? J:j-s.top ()-1; - if(H*w>result) result=h*W; - } - S.push (j); - } - } in returnresult; - } to};
1 classSolution {2 Public:3 intMaximalrectangle (vector<vector<Char>>&matrix) {4 if(Matrix.empty ())return 0;5 Const intm=matrix.size ();6 Const intn=matrix[0].size ();7vector<int> Left (n,0), right (N,n), Height (n,0);8 intresult=0;9 for(intI=0; i<m; i++){Ten intcur_left=0, cur_right=N; One for(intj=0; j<n; J + +){ A if(matrix[i][j]=='1') height[j]++; - Elseheight[j]=0; - } the for(intj=0; j<n; J + +){ - if(matrix[i][j]=='1') left[j]=Max (Left[j], cur_left); - Else{left[j]=0; cur_left=j+1; } - } + for(intj=n-1; j>=0; j--){ - if(matrix[i][j]=='1') right[j]=min (right[j], cur_right); + Else{right[j]=n; cur_right=J;} A } at for(intj=0; j<n; J + +){ -Result=max (result, (Right[j]-left[j]) *height[j]); - } - } - returnresult; - } in};
Leave pit
Leetcode 85. Maximal Rectangle