Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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.
public class Solution {
public int BFS(char[][] matrix, int i, int j, int len, int wid) {
int ret = 1;
for (int k = 1; k < Math.min(len - i, wid - j); k++) {
for (int g = 0; g <= k; g++) {
if (matrix[i + k][j + g] == '0' || matrix[i + g][j + k] == '0') {
return k * k;
}
}
ret = (k + 1) * (k + 1);
}
return ret;
}
public int maximalSquare(char[][] matrix) {
int len = matrix.length;
if(len == 0){
return 0;
}
int wid = matrix[0].length;
int ret = 0;
for(int i = 0; i<len; i++){
for(int j = 0; j<wid; j++){
if(matrix[i][j] == '1'){
ret = Math.max(ret, BFS(matrix, i, j, len, wid));
}
}
}
return ret;
}
}
网友评论