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 0Return 4.
、
class Solution {
bool checkboader(vector<vector<char>>& matrix,int rightdownX,int rightdownY,int len)
{
for(int i=rightdownY-len;i<=rightdownY;i++)
if(matrix[i][rightdownX]=='0')
return false;
for(int i=rightdownX-len;i<=rightdownX;i++)
if(matrix[rightdownY][i]=='0')
return false;
return true;
}
void get_bigger(vector<vector<char>>& matrix,int leftupX,int leftupY,int&maxsquare)
{
int kk=1;
while(leftupX+kk<matrix[0].size()&&leftupY+kk<matrix.size()&&
checkboader(matrix,leftupX+kk,leftupY+kk,kk))
kk++;
//if(leftupX+kk>=matrix[0].size()||leftupY+kk>=matrix.size())
if(kk>maxsquare)
maxsquare=kk;
}
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty())
return 0;
if(matrix[0].empty())
return 0;
int maxsquare=0;
for(int i=0;i<matrix.size()-maxsquare;i++)
for(int j=0;j<matrix[0].size()-maxsquare;j++)
{
if(matrix[i][j]=='1')
{
get_bigger(matrix,j,i,maxsquare);
}
//cout<<i<<" "<<j<<endl;
}
return maxsquare*maxsquare;
}
};
accepted