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 0Return 4.
Solution:
Method 1: Dynamic Programming
dp[i][j]: max size to form a square from this point as lower right point.
dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - 1], dp[i][j - 1]) + 1
Code:
public class Solution { public int maximalSquare(char[][] matrix) { int max = 0; if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) { return 0; } int m = matrix.length; int n = matrix[0].length; int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { dp[i][j] = matrix[i][j] - '0'; } else if (matrix[i][j] == '0') { dp[i][j] = 0; } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; } max = Math.max(max, dp[i][j]); } } return max * max; } }
Method 2: Optimized with rolling array
Code:
public class Solution { public int maximalSquare(char[][] matrix) { int max = 0; if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) { return 0; } int m = matrix.length; int n = matrix[0].length; int[][] dp = new int[2][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { dp[i % 2][j] = matrix[i][j] - '0'; } else if (matrix[i][j] == '0') { dp[i % 2][j] = 0; } else { dp[i % 2][j] = Math.min(Math.min(dp[(i - 1) % 2][j], dp[i % 2][j - 1]), dp[(i - 1) % 2][j - 1]) + 1; } max = Math.max(max, dp[i % 2][j]); } } return max * max; } }