题目描述
在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。
样例描述
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
思路
- 动态规划
要想面积最大,也就是边长最大。先进行状态表示如下:
由正方形四个点的状态表示关系,不难得出
最后可以得出完整的递推式,
代码
class Solution {
public int maximalSquare(char[][] matrix) {
int maxSize = 0;
int m = matrix.length, n = matrix[0].length;
if (matrix == null || m == 0 || n == 0) {
return maxSize;
}
int f[][] = new int[m][n];
for (int i = 0; i < m; i ++ ) {
for (int j = 0; j < n; j ++ ) {
//只有当前是'1' 才寻找
if (matrix[i][j] == '1') {
//边界情况
if (i == 0 || j == 0) {
f[i][j] = 1;
}else {
//其余情况 按照递推转移方程
f[i][j] = Math.min(Math.min(f[i - 1][j], f[i][j - 1]), f[i - 1][j - 1]) + 1;
}
//更新最大的边
maxSize = Math.max(maxSize, f[i][j]);
}
}
}
return maxSize * maxSize;
}
}