Problem Description:

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

Analysis:

Algorithm 1:

This problem is very similar to No.85 Maximal Rectangle problem. In fact I tried to solve this problem right after Maximal Rectangle problem, so I naturally came up with a solution based upon that algorithm. The majority of the code remain the same, except when updating the maximum area after each row iteration, instead of calculate

1
res = (right[i][j] - left[i][j]) * height[i][j];

We compare height[i][j] and right[i][j] - left[i][j] and take the smaller one as square’s side, then the area is size squared.
1
2
int r = Math.min(right[i][j] - left[i][j], height[i][j]);
res = r * r;

Algorithm 2:

Still dynamic programming, but this one only uses one matrix.

MaximalSquare.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MaximalSquare {
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0) return 0;
int res = 0;
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];

for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;ß
}
res = Math.max(res, dp[i][j]);
}
}
return res * res;
}
}