题目:
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.
题目链接:https://leetcode.com/problems/maximal-square/。
这一题有点相似:LeetCode OJ 之 Maximal Rectangle (最大的矩形)。可是解题方法全然不同。
思路:
动态规划。设f[i][j]表示包含当前点的正方形的最大变长,有递推关系例如以下:
f[0][j] = matrix[0][j]
f[i][0] = matrix[i][0]
For i > 0 and j > 0:
if matrix[i][j] = 0, f[i][j] = 0;
if matrix[i][j] = 1, f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1.
代码1:
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix)
{
int row = matrix.size();
if(row == 0)
return 0;
int col = matrix[0].size();
vector<vector<int> > f(row , vector<int>(col , 0));
int maxsize = 0; //最大边长
for(int i = 0 ; i < row ; i++)
{
for(int j = 0 ; j < col ; j++)
{
if(i == 0 || j == 0)
f[i][j] = matrix[i][j]-'0';
else
{
if(matrix[i][j] == '0')
f[i][j] = 0;
else
f[i][j] = min(min(f[i-1][j] , f[i][j-1]) , f[i-1][j-1]) + 1;
}
maxsize = max(maxsize , f[i][j]);
}
}
return maxsize * maxsize;
} };
代码2:
优化空间为一维
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix)
{
int row = matrix.size();
if(row == 0)
return 0;
int col = matrix[0].size(); vector<int> f(col , 0); int tmp1 = 0 , tmp2 = 0; int maxsize = 0; //最大边长
for(int i = 0 ; i < row ; i++)
{
for(int j = 0 ; j < col ; j++)
{
tmp1 = f[j]; //tmp1把当前f[j]保存以下,用来做下一次推断f[i+1][j+1]的左上角f[i-1][j-1]
if(i == 0 || j == 0)
f[j] = matrix[i][j]-'0';
else
{
if(matrix[i][j] == '0')
f[j] = 0;
else
f[j] = min(min(f[j-1] , f[j]) , tmp2) + 1; //这里的tmp2即是代码1的f[i-1][j-1]
}
tmp2 = tmp1 ; //把tmp1赋给tmp2,用来下次for循环求f[j+1]
maxsize = max(maxsize , f[j]);
}
}
return maxsize * maxsize;
} };