题目地址:
https://leetcode.com/problems/maximal-square/
给定一个二维 0 − 1 0-1 0−1矩阵 A A A,求其中最大的全由 1 1 1构成的正方形的面积。
设 f [ i ] [ j ] f[i][j] f[i][j]表示由 A [ i − 1 ] [ j − 1 ] A[i-1][j-1] A[i−1][j−1]为右下角的面积最大的 1 1 1矩阵的边长(即 A A A的前 i i i行和 j j j列的子矩阵中,以右下角为顶点的最大的 1 1 1矩阵的边长)。如果 A [ i − 1 ] [ j − 1 ] = 0 A[i-1][j-1]=0 A[i−1][j−1]=0那显然 f [ i ] [ j ] = 0 f[i][j]=0 f[i][j]=0。否则,首先显然 f [ i ] [ j ] ≤ min { f [ i − 1 ] [ j ] + 1 , f [ i ] [ j − 1 ] + 1 , f [ i − 1 ] [ j − 1 ] + 1 } = min { f [ i − 1 ] [ j ] , f [ i ] [ j − 1 ] , f [ i − 1 ] [ j − 1 ] } + 1 f[i][j]\le \min\{f[i-1][j]+1, f[i][j-1]+1,f[i-1][j-1]+1\}=\min\{f[i-1][j], f[i][j-1],f[i-1][j-1]\}+1 f[i][j]≤min{f[i−1][j]+1,f[i][j−1]+1,f[i−1][j−1]+1}=min{f[i−1][j],f[i][j−1],f[i−1][j−1]}+1。设 x = min { f [ i − 1 ] [ j ] , f [ i ] [ j − 1 ] , f [ i − 1 ] [ j − 1 ] } x=\min\{f[i-1][j], f[i][j-1],f[i-1][j-1]\} x=min{f[i−1][j],f[i][j−1],f[i−1][j−1]},可以看出 A [ i − 1 − x ] [ j − 1 − x ] = 1 A[i-1-x][j-1-x]=1 A[i−1−x][j−1−x]=1,所以 f [ i ] [ j ] ≥ x + 1 f[i][j]\ge x+1 f[i][j]≥x+1。所以 f [ i ] [ j ] = x + 1 f[i][j]=x+1 f[i][j]=x+1。代码如下:
class Solution {
public:
int maximalSquare(vector<vector<char>>& A) {
int res = 0, m = A.size(), n = A[0].size();
int f[m + 1][n + 1];
memset(f, 0, sizeof f);
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) {
if (A[i - 1][j - 1] != '0') {
f[i][j] = min(f[i - 1][j - 1], min(f[i - 1][j], f[i][j - 1])) + 1;
res = max(res, f[i][j]);
}
}
return res * res;
}
};
时空复杂度 O ( m n ) O(mn) O(mn)。