Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.
思路:动态规划
每点记录矩形的最小边长 |
动规,考虑上,左,左上三点的最小边长,取最小的+1 |
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix==null||matrix.length==0) return 0;
int m=matrix.length, n=matrix[0].length, result=0;
int[][] dp = new int[m+1][n+1];
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(matrix[i][j]=='1'){
dp[i+1][j+1] = Math.min(Math.min(dp[i][j],dp[i+1][j]),dp[i][j+1])+1;
result = Math.max(dp[i+1][j+1],result);
}
}
}
return result*result;
}
}