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.
Analysis:
Apply 2D dynamic programming to this problem. Initialize a 2D array dp
where dp[i][j]
represents the side length of the maximum square whose right bottom corner is the cell with index
(
i
,
j
)
(i,j)
(i,j) in the original matrix.
As the following above graph shows, in the cell with index
(
i
,
j
)
(i, j)
(i,j), we enlarge the most limited(smallest) neighboring square as a new square.
d
p
[
i
]
[
j
]
=
{
m
i
n
{
d
p
[
i
−
1
]
[
j
−
1
]
,
d
p
[
i
−
1
]
[
j
]
,
d
p
[
i
]
[
j
−
1
]
}
+
1
(
m
a
t
r
i
x
[
i
]
[
j
]
=
1
)
0
(
m
a
t
r
i
x
[
i
]
[
j
]
=
0
)
dp[i][j] = \begin{cases} min\{dp[i-1][j-1], dp[i-1][j], dp[i][j-1]\} + 1 \ (matrix[i][j] = 1) \\ 0 \ (matrix[i][j] = 0) \end{cases}
dp[i][j]={min{dp[i−1][j−1],dp[i−1][j],dp[i][j−1]}+1 (matrix[i][j]=1)0 (matrix[i][j]=0)
Code:
class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0) {
return 0;
}else{
int M = matrix.length;
int N = matrix[0].length;
int[][] dp = new int[M][N];
for(int i = 0; i < M; i++) {
if(matrix[i][0] == '1') {
dp[i][0] = 1;
}
}
for(int j = 0; j < N; j++) {
if(matrix[0][j] == '1') {
dp[0][j] = 1;
}
}
for(int i = 1; i < M; i++) {
for(int j = 1; j < N; j++) {
if(matrix[i][j] == '1') {
int L = Math.min(dp[i-1][j-1], Math.min(dp[i][j-1], dp[i-1][j]));
dp[i][j] = L + 1;
}
}
}
int maxL = 0;
for(int i = 0; i < M; i++) {
for(int j = 0; j < N; j++) {
if(dp[i][j] > maxL) {
maxL = dp[i][j];
}
}
}
return maxL * maxL;
}
}
}