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.
Code
Always remember to get rid of invalid input and deal with corner cases in the first place. We have the following state equations:
P[0][j] = matrix[0][j] (topmost row);
P[i][0] = matrix[i][0] (leftmost column);
For i > 0 and j > 0:
if matrix[i][j] = 0, P[i][j] = 0;
if matrix[i][j] = 1, P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1.
Thus, we have the following straightforward code:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size();
if (!m) return 0;
int n = matrix[0].size();
vector<vector<int> > size(m, vector<int>(n, 0));
int maxsize = 0;
for (int j = 0; j < n; j++) {
size[0][j] = matrix[0][j] - '0';
maxsize = max(maxsize, size[0][j]);
}
for (int i = 1; i < m; i++) {
size[i][0] = matrix[i][0] - '0';
maxsize = max(maxsize, size[i][0]);
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == '1') {
size[i][j] = min(size[i - 1][j - 1], min(size[i - 1][j], size[i][j - 1])) + 1;
maxsize = max(maxsize, size[i][j]);
}
}
}
return maxsize * maxsize;
}
Actually, space can be saved by using a one-dimension array
```
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
//Get rid of invalid input
int row = matrix.size();
if(!row)
return 0;
int col = row > 0 ? matrix[0].size() : 0;
vector<int> dp(row+1,0);
int maxsize = 0, pre = 0;
for(int j = 0; j < col; j++)
for(int i = 1; i <= row; i++){
int tmp = dp[i];
if(matrix[i - 1][j] == '1'){
dp[i] = min(dp[i], min(dp[i - 1], pre)) + 1;
maxsize = max(maxsize, dp[i]);
}
else
dp[i] = 0;
pre = tmp;
}
return maxsize * maxsize;
}
};