Maximal Square
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.
1 class Solution { 2 public: 3 int maximalSquare(vector<vector<char>>& matrix) { 4 int n=matrix.size(); 5 if(n<1) return 0; 6 int m=matrix[0].size(); 7 if(m<1) return 0; 8 vector<vector<int>> size(n,vector<int>(m,0)); 9 int maxnum=0; 10 int i; 11 for(i=0;i<n;i++) 12 { 13 if(matrix[i][0]=='1') 14 { 15 size[i][0]=1; 16 maxnum=1; 17 } 18 } 19 for(i=0;i<m;i++) 20 { 21 if(matrix[0][i]=='1') 22 { 23 size[0][i]=1; 24 maxnum=1; 25 } 26 } 27 28 int j; 29 for(i=1;i<n;i++) 30 { 31 for(j=1;j<m;j++) 32 { 33 if(matrix[i][j]=='1') 34 { 35 size[i][j]=min(size[i-1][j-1],min(size[i-1][j],size[i][j-1]))+1; 36 if(maxnum<size[i][j]) 37 maxnum=size[i][j]; 38 } 39 else 40 size[i][j]=0; 41 } 42 } 43 return maxnum*maxnum; 44 } 45 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=