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.
本题是正方形,
矩形:85. Maximal Rectangle
Solution:DP
思路:dp[i][j]存的是 以i-1, j-1作为右下点结束 的最长正方形边长
则状态转移方程为dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
Time Complexity: O(mn) Space Complexity: O(mn)
Solution Code:
class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int max_length = 0;
for(int i = 1; i < m + 1; i++) {
for(int j = 1; j < n + 1; j++) {
int row = i - 1;
int col = j - 1;
if(matrix[row][col] == '1') {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
if(dp[i][j] > max_length) {
max_length = dp[i][j];
}
}
}
}
return max_length * max_length;
}
}