# Middle-题目103：221. 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 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.

dp[i][j]=min(dp[i1][j],dp[i1][j1],dp[i][j1])+1$dp[i][j] = min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1])+1$

public class Solution {
public int maximalSquare(char[][] matrix) {
int row = matrix.length;
if(row == 0)
return 0;
int col = matrix[0].length;
int maxSquare = 0;
int[][] dp = new int[row][col];
for(int i = 0 ;i<col;i++) {
dp[0][i]=matrix[0][i]-'0';
if(matrix[0][i] == '1')
maxSquare = 1;
}
for(int i = 0;i<row;i++) {
dp[i][0]=matrix[i][0]-'0';
if(matrix[i][0] == '1')
maxSquare = 1;
}
for(int i = 1;i<row;i++) {
for(int j=1;j<col;j++) {
if(matrix[i][j] == '1')
dp[i][j] = Math.min(dp[i-1][j], Math.min(dp[i-1][j-1], dp[i][j-1]))+1;
if(dp[i][j] > maxSquare)
maxSquare = dp[i][j];
}
}
return maxSquare*maxSquare;
}
}

14ms,beats 58.15%,众数17ms,11.81%

06-18 1995

08-10 568

06-05 1.1万

03-24 692

10-04 4859

03-13 41

07-08 80

04-11 140

07-12 2

03-03 389