题目:https://leetcode-cn.com/problems/maximal-square/
思路:动态规划
1. 如果m[i][j]==0,dp[i][j] = 0;
2.如果m[i][j] == 1
1.在边缘,(i=0 || j=0),令dp[i][j]=1
2.递推方程:dp[i][j] = min(dp[i][j-1],dp[i-1][j],d[[i-1][j-1]) + 1
(上方,左方,左上方的最小值 + 1)
代码:
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.size() == 0 || matrix[0].size()==0) return 0;
int row=matrix.size(),col = matrix[0].size();
vector<vector<int>>dp(row,vector<int>(col));
int maxn = 0;
for(int i=0;i<row;i++){
for(int j = 0;j<col;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-1][j-1]),dp[i][j-1]) + 1;
}
maxn = max(maxn,dp[i][j]);
}
}
}
return maxn*maxn;
}
};