221. 最大正方形
作者:互联网
221. 最大正方形
难度中等878
在一个由 '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
示例 2:
输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:
输入:matrix = [["0"]]
输出:0
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
为'0'
或'1'
/**
* @param {character[][]} matrix
* @return {number}
*/
var maximalSquare = function(matrix) {
let arr = [];
for(let i = 0; i<matrix.length; i++){
arr.push([])
for(let j = 0; j<matrix[0].length; j++){
arr[i].push(0);
}
}
let checkBefore = function(x, y, len){
let leftLen = 0;
let rightLen = 0;
for(let i = 1; i<=len; i++){
if(x-i<0) break;
if( matrix[x-i][y]==1){
leftLen++;
}else break;
}
for(let i = 1; i<=len; i++){
if(y-i<0) break;
if(matrix[x][y-i]==1){
rightLen++;
}else break;
}
let min = leftLen<rightLen?leftLen:rightLen;
return (+min+1)*(+min+1);
}
for(let i = 0; i<matrix.length; i++){
for(let j = 0; j<matrix[0].length; j++){
if(matrix[i][j]==0) continue;
if(i<1|| j<1 || matrix[i-1][j-1]==0 ) {
arr[i][j]=1;
continue;
}else{
arr[i][j] = checkBefore(i, j, arr[i-1][j-1]**(1/2));
}
}
}
let max = 0;
for(let i = 0; i<matrix.length; i++){
// console.log(arr[i])
for(let j = 0; j<matrix[0].length; j++){
if(arr[i][j]>max) max = arr[i][j];
}
}
return max;
};
标签:arr,最大,示例,max,正方形,let,leftLen,221,matrix 来源: https://blog.csdn.net/weixin_45440200/article/details/120490637