Given a 2D binary matrix filled with 0\'s and 1\'s, find the largest square containing only 1\'s and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
方法1:暴力算法(brute force)
class Solution {
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int max = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int temp = getMaxSquare(matrix, i, j);
if (max < temp) {
max = temp;
}
}
}
return max;
}
int getMaxSquare(char[][] matrix, int rowIndex, int colIndex) {
int row = matrix.length;
int col = matrix[0].length;
if (matrix[rowIndex][colIndex] == \'0\') {
return 0;
}
int length = 1;
int maxSize = Math.min(row-rowIndex, col-colIndex);
for (int size = 1; size < maxSize; size++) {
for (int i = rowIndex; i <= rowIndex + size; i++) {
int newCol = colIndex + size;
if (matrix[i][newCol] == \'0\') {
return length*length;
}
}
for (int j = colIndex; j <= colIndex + size; j++) {
int newRow = rowIndex + size;
if (matrix[newRow][j] == \'0\') {
return length*length;
}
}
length ++;
}
return length * length;
}
}
时间复杂度:O(n^4)
空间复杂度:O(n)
继续阅读与本文标签相同的文章
-
AI+5G科技创新 视频行业呈现轻应用化趋势
2026-05-14栏目: 教程
-
1.98亿滴滴用户添加了紧急联系人 每天百万个订单行程分享给亲友
2026-05-14栏目: 教程
-
工程院院士刘韵洁:5G前景很大,但主要是行业应用
2026-05-14栏目: 教程
-
陆奇:看好5G技术,但应用好5G还需要时间
2026-05-14栏目: 教程
-
在Visual Studio中使用clang-tidy进行代码分析
2026-05-14栏目: 教程
