Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
Example:
Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4
Solution:
Dynamic Programming.
When matrix[i][j] is ‘1’,
dp[i][j] = min(matrix[i -1][j],
matrix[i][j – 1],
matrix[i – 1][j -1]) + 1.
The maximal square will be the maximum dp[i][j] square.
class Solution { public int maximalSquare(char[][] matrix) { int n = matrix.length; if (n == 0) { return 0; } int m = matrix[0].length; if (m == 0) { return 0; } int[][] cmat = new int[n][m]; final int INF = Integer.MAX_VALUE; int maxv = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (matrix[i][j] == '0') { cmat[i][j] = 0; } else { int minv = INF; if (i > 0) { minv = Math.min(minv, cmat[i-1][j]); } else { minv = 0; } if (j > 0) { minv = Math.min(minv, cmat[i][j-1]); } else { minv = 0; } if (i > 0 && j > 0) { minv = Math.min(minv, cmat[i-1][j-1]); } else { minv = 0; } cmat[i][j] = minv + 1; maxv = Math.max(maxv, cmat[i][j]); } } } return maxv * maxv; } }
Time complexity: O(n).
Space complexity: O(n).