Maximal Square
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
Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
The DP thought part of this question draws on the jianchao.li.fighter.
Here's the idea: building a two-dimensional array len,len[i][j] represents the length of the largest square in the lower-right corner (I,J).
The recurrence relationship is len[i][j] = min (min (len[i-1][j], len[i][j-1]), len[i-1][j-1]) + 1;
As indicated:
The maximum square side length (I,J) is the lower right corner, depending on the surrounding three positions (I-1,j), (i,j-1), (i-1,j-1), which is exactly the minimum edge length of the three to expand 1 bits.
If the minimum side length of the three is 0, then (i,j) from the side length of 1 blocks.
classSolution { Public: intMaximalsquare (vector<vector<Char>>&matrix) { if(Matrix.empty () | | matrix[0].empty ())return 0; intm =matrix.size (); intn = matrix[0].size (); intMaxLen =0; Vector<vector<int> > Len (M, vector<int> (n,0)); //First Row for(inti =0; I < n; i + +) {len[0][i] = (int) (matrix[0][i]-'0'); if(len[0][i] = =1) MaxLen=1; } //First Col for(inti =0; I < m; i + +) {len[i][0] = (int) (matrix[i][0]-'0'); if(len[i][0] ==1) MaxLen=1; } for(inti =1; I < m; i + +) { for(intj =1; J < N; J + +) { if(Matrix[i][j] = ='0') Len[i][j]=0; Else{Len[i][j]= Min (min (len[i-1][J], len[i][j-1]), len[i-1][j-1]) +1; MaxLen=Max (Len[i][j], maxlen); } } } returnMaxLen *MaxLen; }};
"Leetcode" 221. Maximal Square