最大正方形
在一个由 '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
题解
可以使用动态规划降低时间复杂度。我们用 \(dp[i][j]\)表示以下标 \(i\) 和 \(j\) 为全部包含“1”的正方形的右下角。则当\(matrix[i][j]==1\)时有状态转移方程:\(dp[i][j] = min(dp[i-1][j], dp[i], [j-1], dp[i-1][j-1])+1\)
当\(matrix[i][j]==0\)时,\(dp[i][j]=0\)
最后,还需考虑边界条件,即当\(i=0\) 或 \(j=0\)时,若 \(matrix[i][j]=1\) ,则 \(dp[i][j]=1\),否则\(dp[i][j]=0\)
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return 0;
}
int maxSide = 0;
int rows = matrix.size(), columns = matrix[0].size();
vector<vector<int>> dp(rows, vector<int>(columns));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (matrix[i][j] == '1') {
if (i == 0 || j == 0) {
dp[i][j] = 1;
} else {
dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
}
maxSide = max(maxSide, dp[i][j]);
}
}
}
int maxSquare = maxSide * maxSide;
return maxSquare;
}
};
标签:matrix,maxSide,int,正方形,二维,dp,size
From: https://www.cnblogs.com/parallel-138/p/17201737.html