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 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Return 4.
dp问题,用一个dp[i][j]保存matrix[i][j]作为右下节点的时候的最大矩形的边长
if (matrix[i][j] == '0') dp[i][j] = 0;
else dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
1 public class Solution { 2 public int maximalSquare(char[][] matrix) { 3 int res = 0; 4 if (matrix==null || matrix.length==0 || matrix[0].length==0) return res; 5 int[][] dp = new int[matrix.length][matrix[0].length]; 6 int maxEdge = 0; 7 for (int i=0; i<matrix.length; i++) { 8 if (matrix[i][0] == '1') dp[i][0] = 1; 9 else dp[i][0] = 0; 10 maxEdge = Math.max(maxEdge, dp[i][0]); 11 } 12 for (int j=1; j<matrix[0].length; j++) { 13 if (matrix[0][j] == '1') dp[0][j] = 1; 14 else dp[0][j] = 0; 15 maxEdge = Math.max(maxEdge, dp[0][j]); 16 } 17 for (int i=1; i<matrix.length; i++) { 18 for (int j=1; j<matrix[0].length; j++) { 19 if (matrix[i][j] == '0') { 20 dp[i][j] = 0; 21 continue; 22 } 23 dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1; 24 maxEdge = Math.max(maxEdge, dp[i][j]); 25 } 26 } 27 return maxEdge * maxEdge; 28 } 29 }