Subject to the effect: in a two-dimensional matrix consisting of 0 and 1, to find the maximum square contains only 1, and returns its area.
Analysis: Dynamic Programming.
dp [i] [j] - In matrix [i - 1] [j - 1] at the lower right corner of the square is a maximum side length of a square
Initialization: dp [i] [j] = 0
State transition equation: If the matrix [i - 1] [j - 1] == '1', the update dp [i] [j] = min (dp [i - 1] [j - 1], min (dp [i ] [j - 1], dp [i - 1] [j])) + 1
Results: max {dp [i] [j]} * max {dp [i] [j]}
Optimization: reduce space complexity, the dp become a one-dimensional array. Because dp [i] [j] except the upper row and [i-1] [j-1] & [i-1] [j], that is the former and its related prev, i.e., so long as the record prev can.
Code:
Basic dynamic rules:
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.size() == 0) return 0;
vector<vector<int>> dp(matrix.size() + 1,vector<int>(matrix[0].size() + 1));
int maxLen = 0;
for(int i = 1;i <= matrix.size();i++){
for(int j = 1;j <= matrix[0].size();j++){
if(matrix[i - 1][j - 1] == '1'){
dp[i][j] = min(dp[i - 1][j - 1],min(dp[i][j - 1],dp[i - 1][j])) + 1;
maxLen = max(maxLen,dp[i][j]);
}
}
}
return maxLen * maxLen;
}
};
Optimization of dynamic rules:
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.size() == 0) return 0;
vector<int> dp(matrix[0].size() + 1);
int maxLen = 0,prev = 0;
for(int i = 1;i <= matrix.size();i++){
for(int j = 1;j <= matrix[0].size();j++){
int tmp = dp[j];
if(matrix[i - 1][j - 1] == '1'){
dp[j] = min(prev,min(dp[j - 1],dp[j])) + 1;
maxLen = max(maxLen,dp[j]);
}
else dp[j] = 0;
prev = tmp;
}
}
return maxLen * maxLen;
}
};