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.
Problem Solving Ideas:
DP problem, with a dp[i][j] save Matrix[i][j] as the bottom right node at the time of the maximum rectangle edge length, Java implementation is as follows:
public int maximalsquare (char[][] matrix) {if (Matrix.length = = 0 | | matrix[0].length = = 0) return 0;int res = 0;int[] DP = New Int[matrix[0].length];for (int i = 0; i < matrix[0].length; i++) if (matrix[0][i] = = ' 1 ') {dp[i] = 1; Res=1;} for (int i = 1; i < matrix.length; i++) {dp[0] = matrix[i][0] = = ' 1 '? 1:0;res=math.max (res, dp[0]); for (int j = 1; j < Matrix[0].length; J + +) {if (matrix[i][j]== ' 0 ') Dp[j]=0;else if (dp[j] = = dp[j-1]&& Matrix[i-dp[j]][j-dp[j]] = = ' 0 ') {dp[j] = Mat H.min (Dp[j], dp[j-1]);} ELSEDP[J] = Math.min (Dp[j], dp[j-1]) + 1;res=math.max (res, dp[j]);}} return res*res; }
Java for Leetcode 221 maximal Square