在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
示例 2:
输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:
输入:matrix = [["0"]]
输出:0
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] 为 '0' 或 '1'
思想:DP
取最小值其实是x轴y轴和对角线上三个地方都要判断过
题目
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int n = matrix.size(), m = matrix[0].size();//n x m
int d[n][m];//dp数组
int res = 0;//最大面积
//初始化
for(int i = 0; i < m; i ++)
{
d[0][i] = matrix[0][i] == '1'? 1: 0;
res = max(res, d[0][i]);
}
for(int i = 0; i < n; i ++)
{
d[i][0] = matrix[i][0] == '1'? 1: 0;
res = max(res, d[i][0]);
}
for(int i = 1; i < n; i ++)
for(int j = 1; j < m; j ++)
{
if(matrix[i][j] == '0') d[i][j] = 0;
else
{
d[i][j] = min(min(d[i - 1][j], d[i][j - 1]),d[i - 1][j - 1]) + 1;
res = max(res, d[i][j]);
}
}
return res * res;
}
};