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.
/*
* 动态规划的算法
*if(m[i][j] = 1) d[i][j] = min(d[i-1][j-1], d[i][j-1], d[i-1][j]) + 1
*m[i][j] = 0; d[i][j] = 0;
*初始化 d[0][j] = m[0][j]; d[i][0] = m[i][0];
*优化思路用一行d[j] 进行
*int preNode = d[0];
*d[0] = m[i][0];
* for(int j = 1; j < n; j++)
* {
* if(m[i][j] = 1) int temp = min(preNode, d[j-1], d[j]) + 1;
* preNode = d[j];
* d[j] = temp;
* }
*错误1:没有考虑<1,0,1,1>向量 ;把矩阵想成等宽高的
*/int min(int a, int b)
{
return a < b ? a : b;
}
int min(int a, int b, int c)
{
return min(min(a,b),min(b,c));
}
int maximalSquare(vector<vector<char>>& m) {
if(m.size() == 0) return 0;
int m_size = m.size();
// if(m_size == 1) return (m[0][0] == '0') ? 0 : 1;
int* d = new int[m[0].size()];
int max = 0;
//init
for(int i = 0; i < m[0].size(); i++)
{
d[i] = (m[0][i] == '0') ? 0 : 1;
if(d[i] > max) max = d[i];
}
//循环
for(int l = 1; l < m_size; l++) //从第1行開始
{
int preNode = d[0];
d[0] = (m[l][0] == '0') ? 0 : 1;
for(int j = 1; j < m[0].size(); j++)
{
if(m[l][j] == '0')
{
preNode = d[j];
d[j] = 0;
}
else //m[l][j] = 1时
{
int temp = min(preNode, d[j-1], d[j]);//d[l-1][j-1], d[l][j-1], d[l-1][j]
preNode = d[j];
d[j] = temp + 1;
if(d[j] > max)
{
max = d[j];
}
}
}
}
delete d;
return max*max;
}
版权声明:本文博主原创文章。博客,未经同意不得转载。