221. Maximal Square
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.
题目是让求给定的矩阵中由1构成的正方形的最大面积,找到求一个点(i,j)的公式,如果matrix[i][j] == '0',那么以(i, j)为断点的正方形边长为0,如果matrix[i][j] == '1';
class Solution {
public:
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;
}
};
压缩上面的矩阵
c++