在一个二维01矩阵中找到全为1的最大正方形
样例
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
返回 4
class Solution {
public:
/*
* @param matrix: a matrix of 0 and 1
* @return: an integer
*/
int maxSquare(vector<vector<int>>& matrix) {
// write your code here
if (matrix.size() == 0 || matrix[0].size() == 0) {
return 0;
}
vector<vector<int>> squares(matrix.size(), vector<int>(matrix[0].size(), 0));
for (int i = 0; i < matrix.size(); i++) {
squares[i][0] = matrix[i][0];
}
for (int j = 0; j < matrix[0].size(); j++) {
squares[0][j] = matrix[0][j];
}
for (int i = 1; i < matrix.size(); i++) {
for (int j = 1; j < matrix[0].size(); j++) {
if (matrix[i][j] == 1) {
int tmp = min(squares[i - 1][j], squares[i][j - 1]);
squares[i][j] = min(tmp, squares[i - 1][j - 1]) + 1;
} else {
squares[i][j] = 0;
}
}
}
int max_square = INT_MIN;
for (int i = 0; i < squares.size(); i++) {
for (int j = 0; j < squares[0].size(); j++) {
max_square = max(max_square, squares[i][j]);
}
}
return max_square * max_square;
}
};