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 title is to find the largest square with an element that is all 1. Using DP, the recursive type is:
DP[I][J] = Math.min (Dp[i-1][j],math.min (dp[i][j-1],dp[i-1][j-1])) + 1;
DP[I][J] Indicates the length of the square that appears at that position, dp[i][j] to form a new square, only from the previous left, upper, top left three inside to take the edge length of the smallest plus matrix[i][j] 1, that is, edge length +1.
1 Public classSolution {2 Public intMaximalsquare (Char[] matrix) {3 if(Matrix = =NULL|| Matrix.length = = 0 | | Matrix[0].length = = 0)return0;4 intm = Matrix.length,n = Matrix[0].length;5 int[] DP =New int[m][n];6 intLen = 0;7 for(inti = 0; i<m; i++){8 if(matrix[i][0] = = ' 1 '){9Dp[i][0] = 1;TenLen = 1; One } A } - for(inti = 0; i<n; i++){ - if(Matrix[0][i] = = ' 1 '){ theDp[0][i] = 1; -Len = 1; - } - } + for(inti = 1; I < m; i++){ - for(intj = 1; J < N; J + +){ + if(Matrix[i][j] = = ' 1 '){ ADP[I][J] = Math.min (Dp[i-1][j],math.min (dp[i][j-1],dp[i-1][j-1])) + 1; atlen = dp[i][j] > len?Dp[i][j]: len; - } - } - } - returnlen*Len; - } in}
221. Maximal Square Java Solutions