标签:
Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest square containing all 1‘s and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
dp[i][j]表示以坐标(i,j)为右下角的形成的正方形的最大边长。
dp[i][j]=min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1;
1 class Solution { 2 public: 3 int maximalSquare(vector<vector<char>>& matrix) { 4 5 if(matrix.empty()) return 0; 6 int M=matrix.size(); 7 int N=matrix[0].size(); 8 int result=0; 9 10 vector<vector<int>> dp(M,vector<int>(N,0)); 11 12 for(int j=0;j<N;++j) 13 if(matrix[0][j]==‘1‘) 14 { 15 dp[0][j]=1; 16 result=1; 17 } 18 for(int i=0;i<M;++i) 19 if(matrix[i][0]==‘1‘) 20 { 21 dp[i][0]=1; 22 result=1; 23 } 24 25 for(int i=1;i<M;++i) 26 for(int j=1;j<N;++j) 27 if(matrix[i][j]==‘1‘) 28 { 29 dp[i][j]=min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1; 30 res=max(result,dp[i][j]); 31 } 32 33 return result*result; 34 35 36 } 37 };
标签:
原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4721450.html