[LeetCode] 221. Maximal Square

Given an m x n binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Example 1:
Example 1

Input: matrix = [[“1”,”0”,”1”,”0”,”0”],[“1”,”0”,”1”,”1”,”1”],[“1”,”1”,”1”,”1”,”1”],[“1”,”0”,”0”,”1”,”0”]]
Output: 4

Example 2:
Example 2

Input: matrix = [[“0”,”1”],[“1”,”0”]]
Output: 1

Example 3:
Input: matrix = [[“0”]]
Output: 0

Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] is ‘0’ or ‘1’.

最大正方形。

在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。

思路

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。这是一道矩阵类的DP问题。dp[i][j] 的定义是以坐标 [i][j] 为右下角的点组成的正方形的最大边长。状态转移方程是dp(i, j) = min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1)) + 1。这样的题目练多了才会有思路。

复杂度

时间O(n^2)
空间O(n^2)

代码

Java一维实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
int n = m > 0 ? matrix[0].length : 0;
int[] dp = new int[n + 1];
int max = 0;
int prev = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int temp = dp[j];
if (matrix[i - 1][j - 1] == '1') {
dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;
max = Math.max(max, dp[j]);
} else {
dp[j] = 0;
}
prev = temp;
}
}
return max * max;
}
}

Java二维实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m + 1][n + 1];
int res = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j] = min(
dp[i - 1][j] + 1,
dp[i][j - 1] + 1,
dp[i - 1][j - 1] + 1
);
res = Math.max(res, dp[i][j]);
}
}
}
return res * res;
}

private int min(int a, int b, int c) {
return Math.min(a, Math.min(b, c));
}
}

相关题目

1
2
3
4
5
84. Largest Rectangle in Histogram
85. Maximal Rectangle
221. Maximal Square
1277. Count Square Submatrices with All Ones
1727. Largest Submatrix With Rearrangements

[LeetCode] 221. Maximal Square
https://shurui91.github.io/posts/3979275054.html
Author
Aaron Liu
Posted on
April 28, 2020
Licensed under