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)
源码github地址:https://github.com/zhangyu345293721/leetcode