在一个由 ‘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’
题解
动态规划,f[i][j]代表以i,j为下表最大能构成的正方向
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int res = 0;
int n = matrix.size(),m = matrix[0].size();
vector<vector<int> >f(n + 1,vector<int>(m + 1, 0));
for(int i = 1;i <= n;i ++){
for(int j = 1;j <= m;j ++){
if(matrix[i - 1][j - 1] == '1')f[i][j] = min(f[i - 1][j],min(f[i][j - 1],f[i - 1][j - 1])) + 1;
else f[i][j] = 0;
res = max(res,f[i][j]);
}
}
return res * res;
}
};