221. Maximal Square(动态规划)

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4





dp[i][j] =  min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
dp(i, j) 是以 matrix(i - 1, j - 1) 为 右下角 的正方形的最大边长

 

 





 1 class Solution {
 2 public:
 3     int maximalSquare(vector<vector<char>>& matrix) {
 4         int n = matrix.size();
 5         if(n==0) return 0;
 6         int m = matrix[0].size();
 7         vector<vector<int> > dp(n+1,vector<int>(m+1,0));
 8         int res =0;
 9         for(int i = 1;i <=n;i++)
10             for(int j = 1;j<=m;j++){
11 
12                 if(matrix[i-1][j-1]=='1')
13                     dp[i][j] =  min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1;
14                     res  = max(res,dp[i][j]);
15                 }
16          
17         return res*res;
18     }
19     
20 };

 

posted @ 2019-02-26 20:08  乐乐章  阅读(109)  评论(0编辑  收藏  举报