class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int row = matrix.size();
if(row == 0)
return 0;
int col = matrix[0].size();
int i = 0, j = 0;
vector<vector<int>> CountOnes;
CountOnes.resize(row);
for(int i = 0;i<row;i++)
CountOnes[i].resize(col);
//初始化,计算包括matrix[i][j]的连续的1的数量和
for(i = 0;i<row;i++)
for(j = 0;j<col;j++)
CountOnes[i][j] = (matrix[i][j] == '0')?0:((j == 0)?1:(CountOnes[i][j-1]+1));
//update matrix
int maxOnes = 0; //统计1的最大矩阵数量
for(j = 0;j<col;j++)
{
for(i = 0;i<row;i++)
{
if(CountOnes[i][j] == 0)
continue;
int k = i-1;
int lines = 1;
while(k>=0)
{
if(CountOnes[k][j]>=CountOnes[i][j])
lines++;
else
break;
k--;
}
k = i + 1;
while(k <row)
{
if(CountOnes[k][j]>=CountOnes[i][j])
lines++;
else
break;
k++;
}
if(lines >= CountOnes[i][j])
{
int num = CountOnes[i][j]*CountOnes[i][j];
if(num > maxOnes)
maxOnes = num;
}
}
}
return maxOnes;
}
};
LeetCode || Maximal Square
最新推荐文章于 2022-03-11 22:04:44 发布