Description:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.———————————————————————————————————————————————————
Solution:
题意:在给定由“0”和“1”组成的数组中找到最大的由“1”组成的正方形。
思路:动态规划。如下图:
为节省空间,注意到这种方法其实只涉及到了dp的第i排和i-1排中的两个元素,于是可以将与matrix同等大小的二维数组dp缩减到长度为matrix列数的一维数组,如下图:
值得注意的是:需要在对dp[i]重新赋值前先保存好dp[i]的值以及在这更之前的prev值,目的是给dp[i+1]使用。因此还要对边界(第0排、第0行)做特殊处理。
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.size() == 0)
return 0;
if (matrix.size() == 1) {
for (int i = 0; i < matrix[0].size(); i++) {
if (matrix[0][i] == '1')
return 1;
}
return 0;
}
int maxValue = 0;
vector<int> dp(matrix[0].size(), 0);
for (int i = 0; i < matrix[0].size(); i++) {
dp[i] = matrix[0][i] - '0';
//cout << dp[i] << " ";
}
// cout << endl;
int leftUp = 0, up = 0, left = 0;
for (int i = 1; i < matrix.size(); i++) {
leftUp = dp[0];
dp[0] = matrix[i][0] - '0';
//cout << dp[0] << " ";
maxValue = maxValue > dp[0] ? maxValue : dp[0];
for (int j = 1; j < matrix[0].size(); j++) {
//cout << i << " " << j << endl;
if (matrix[i][j] == '0') {
dp[j] = 0;
} else {
left = dp[j - 1];
up = dp[j];
dp[j] = min(leftUp, min(left, up)) + 1;
}
leftUp = up;
//cout << dp[j] << " ";
maxValue = maxValue > dp[j] ? maxValue : dp[j];
}
//cout << endl;
}
return maxValue * maxValue;
}
};