原题链接在这里:https://leetcode.com/problems/maximal-square/
题目:
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.
题解:
DP, 状态: 以当前点为右下角的最大都包含1的square边长.
转移方程 如果当前点为1, dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])+1.
初始化dp[m+1][n+1], 多一行一列方便处理边界.
res 一直取maintain dp的最大值.
优化dp成一行, 因为只需要左, 上, 和左斜上三个值. prev 来保存左斜上.
Time Complexity: O(m*n). m = matrix.length, n = matrix[0].length.
Space: O(n).
AC Java:
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
} int res = 0;
int m = matrix.length;
int n = matrix[0].length;
int [] dp = new int[n+1];
int prev = 0; for(int i = 1; i<=m; i++){
for(int j = 1; j<=n; j++){
int temp = dp[j];
if(matrix[i-1][j-1] == '1'){
dp[j] = Math.min(Math.min(dp[j], dp[j-1]), prev) + 1;
}else{
dp[j] = 0;
}
prev = temp;
res = Math.max(res, dp[j]);
}
}
return res*res;
}
}