- 最大正方形
尝试过
中等
相关标签
相关企业
在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。
结果:
测试用例超时
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
cpp
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
// 矩阵的行和列
size_t rows = matrix.size();
size_t cols = matrix.empty() ? 0 : matrix[0].size();
int maxArea = 0; // 最大面积
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
size_t maxLength = min(rows - i, cols - j); // 确保不会越界
for (size_t l = 1; l <= maxLength; l++) {
// 直接检查原始矩阵的子矩阵区域
if (isSquare(matrix, i, j, l)) {
int area = l * l;
if (area > maxArea) {
maxArea = area;
}
}
}
}
}
return maxArea;
}
private:
bool isSquare(const vector<vector<char>>& matrix, int startRow, int startCol, size_t length) {
// 检查是否为全 1 的正方形
for (size_t i = 0; i < length; i++) {
for (size_t j = 0; j < length; j++) {
if (matrix[startRow + i][startCol + j] == '0') {
return false;
}
}
}
return true;
}
};