221. Maximal Square
problem description
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4algorithm thought
code
algorithm analysis
Last updated
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4Last updated
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.size()==0||matrix[0].size()==0)
return 0;
int res=0;
vector<vector<int>> dp(matrix.size(),vector<int>(matrix[0].size(),0));
for(int i=0;i<matrix.size();++i){
for(int j=0;j<matrix[0].size();++j){
if(!i||!j||matrix[i][j]=='0'){
dp[i][j]=static_cast<int>(matrix[i][j]-'0');
}else{
dp[i][j]=min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
}
res=max(res,dp[i][j]);
}
}
return res*res;
}
};