Question
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.
Solution
2-d Array. The changing condition is:
T[i][j] = min (t[i][j-1], t[i-1][j], t[i-1][j-1]) + 1.
1 Public classSolution {2 Public intMaximalsquare (Char[] matrix) {3 if(Matrix = =NULL|| Matrix.length < 1)4 return0;5 introw = matrix.length, column = matrix[0].length, max = 0;6 int[] DP =New int[Row][column];7 //Top Row8 for(inti = 0; I < column; i++) {9 if(Matrix[0][i] = = ' 0 ')TenDp[0][i] = 0; One Else ADp[0][i] = 1; - } - //Left Column the for(inti = 0; i < row; i++) { - if(matrix[i][0] = = ' 0 ') -Dp[i][0] = 0; - Else +Dp[i][0] = 1; - } + //Inside Filling A for(inti = 1; i < row; i++) { at for(intj = 1; J < column; J + +) { - if(Matrix[i][j] = = ' 0 ') { -DP[I][J] = 0; -}Else { - intTMP = Math.min (dp[i][j-1], dp[i-1][j]); -DP[I][J] = math.min (tmp, dp[i-1][j-1]) + 1; in } - } to } + for(inti = 0; i < row; i++) { - for(intj = 0; J < column; J + +) theMax =Math.max (Max, dp[i][j]); * } $ returnMax *Max;Panax Notoginseng } -}
Maximal Square Solution