Maximal Square
Description
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 0Output: 4
Solution(javascript)
/**
* @param {character[][]} matrix
* @return {number}
*/
var maximalSquare = function(matrix) {
const getValue = (row, column) => {
if(row < 0 || row >= matrix.length || column < 0 || column >= matrix[row].lenth) {
return 0
}
return matrix[row][column]
}
let max = 0
for(let i = 0; i < matrix.length; i++) {
for(let j = 0; j < matrix[i].length; j++) {
if(matrix[i][j] === "1") {
matrix[i][j] = 1 + Math.min(
getValue(i,j - 1),
getValue(i-1,j ),
getValue(i-1, j-1)
)
max = Math.max(max, matrix[i][j])
}
}
}
return max * max
};