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 0Return 4.
自以为又是一道动态规划的好入门题,动态规划的第一步就是找状态转移方程,这个很重要。当前前提是你得把问题给分析透了。
递归公式为: f(i, j) = min{ f(i-1, j-1), f(i-1, j), f(i, j-1) },决定一个正方形大小的是他的瓶颈,即最小的那个。
显然f(i,0) = f(0, j) = 0;
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
int max = 0, n = matrix.length, m = matrix[0].length;
// dp(i, j) represents the length of the square
// whose lower-right corner is located at (i, j)
// dp(i, j) = min{ dp(i-1, j-1), dp(i-1, j), dp(i, j-1) }
int[][] dp = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
max = Math.max(max, dp[i][j]);
}
}
}
// return the area
return max * max;
}
并且很巧妙的使用了一个row和column都大一的二维数组,可以避免边界情况的判断。
并且只有在当前是1的时候才有可能取得最大值,其他情况全是默认0