Given a 2D binary matrix filled with 0 's and 1 ' s, find the largest square containing all 1 's and return its area.
For example, given the following matrix:
1 1 1 1 11 0 0 1 0
In the given two-dimensional character array, find out the number of 1 that the rectangle with the maximum total of 1 contains:
Note that this is the equivalent of the area, only ask for the side length is very good to run. Side length with DP very good, this problem in fact with the former Youdao DP problem very much like, later have time to find out, first paste the code:
1 classSolution {2 Public:3 intMaximalsquare (vector<vector<Char>>&matrix) {4 if(!matrix.size () | |! matrix[0].size ())return 0;5vector<vector<int>>DP (Matrix.size (), vector<int> (matrix[0].size (),0));6 intMaxval =0;7 for(inti =0; I < matrix.size (); ++i) {8 if(matrix[i][0] =='1'){9dp[i][0] =1;TenMaxval =1; One}Elsedp[i][0] =0; A } - for(intj =0; J < matrix[0].size (); ++j) { - if(matrix[0][J] = ='1'){ thedp[0][J] =1; -Maxval =1; -}Elsedp[0][J] =0; - } + for(inti =1; I < matrix.size (); ++i) { - for(intj =1; J < matrix[0].size (); ++j) { + if(Matrix[i][j] = ='1'){ ADp[i][j] = min (dp[i-1][j], min (dp[i][j-1], dp[i-1][j-1])) +1; atMaxval =Max (Maxval, Dp[i][j]); -}Else -DP[I][J] =0; - } - } - returnmaxval*Maxval; in } -};
Leetcode oj:maximal Square (maximum rectangle)