题目
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
示例
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
输出: 4
思路
- 用一个数组保存,每个元素作为正方体右下角的元素时,所能得到的最大边长。
- 首先第一行和第一列肯定和二维数组一样。
- 遇到0可以跳过。
- 遇到1,看上面和左面的元素值,上面和左面的元素值都代表自身为右下角的最大正方形的边长,取较小的边长m,假如当前的左边为i、j。则判断i-m、j-m处是否为0。为0的话,当前值为m,否则为m+1。
- 记录最大的边长,返回面积。
代码
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if ( matrix.size() == 0 ) return 0;
int ans = 0;
int rows = matrix.size();
int cols = matrix[0].size();
int dp[rows][cols];
memset( dp, 0, sizeof(dp) );
for ( int i = 0; i < rows; ++i ) {
for ( int j = 0; j < cols; ++j ) {
dp[i][j] = matrix[i][j] - '0';
if ( i == 0 || j == 0 ) {
ans = max( ans, dp[i][j] );
}
else if ( dp[i][j] != 0 ) {
int temp = min( dp[i-1][j], dp[i][j-1] );
if ( temp != 0 )
dp[i][j] = dp[i-temp][j-temp] != 0 ? temp + 1 : temp;
ans = max( ans, dp[i][j] );
}
}
}
ans *= ans;
return ans;
}
};