Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest rectangle containing all ones and return to its area.
Find the largest rectangular region in the 0,1 matrix:
DP problem, you can use an array to write down the number of all 1 before the current line position, and then use a triple loop to find the largest area of the rectangle (i,j) to the lower right corner, and get the maximum value. The complexity of doing this is still relatively high. But the win is simple, and the code looks like this:
1 classSolution {2 Public:3 intMaximalrectangle (vector<vector<Char>>&matrix) {4 if(matrix.size () = =0|| matrix[0].size () = =0)5 return 0;6 intSzrow =matrix.size ();7 intSzcol = matrix[0].size ();8vector<vector<int>> dp (Szrow, vector<int> (Szcol,0));//represents the number of 1 in front of the current line9 for(inti =0; i < Szrow; ++i) {//First element of each row of the first columnTendp[i][0] = matrix[i][0] =='1'?1:0; One } A for(inti =0; i < Szrow; ++i) {//each element of each row behind each column - for(intj =1; J < Szcol; ++j) { -DP[I][J] = matrix[i][j] = ='1'? dp[i][j-1]+1:0; the } - } - intMaxval =0; - for(inti =0; i < Szrow; ++i) { + for(intj =0; J < Szcol; ++j) { - intwidth =Int_max; + for(intK = i; K >=0; --k) { A if(Dp[k][j] = =0) at Break; -width = min (width, dp[k][j]);//find out the width of each square -Maxval = Max (maxval, Width * (i-k +1));//width multiplied by height - } - } - } in returnMaxval; - } to};
First horse on the way others write, feeling written very good, have time to write
Leetcode oj:maximal Rectangle (maximum rectangle)