function maximalSquare(matrix: string[][]): number {
const [m, n] = [matrix.length, matrix[0].length]
let [max, pre] = [0, 0]
const dp = new Array(n).fill(0)
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const tmp = dp[j]
if (matrix[i][j] === '0') dp[j] = 0
else dp[j] = Math.min(pre, dp[j], dp[j - 1] ?? 0) + 1
pre = tmp
max = Math.max(max, dp[j])
}
}
return Math.pow(max, 2)
}
test.each([
{
input: {
matrix: [
['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0'],
],
},
output: 4,
},
{
input: {
matrix: [
['0', '1'],
['1', '0'],
],
},
output: 1,
},
{ input: { matrix: [['0']] }, output: 0 },
{ input: { matrix: [['1']] }, output: 1 },
{
input: {
matrix: [
['0', '0', '0', '1'],
['1', '1', '0', '1'],
['1', '1', '1', '1'],
['0', '1', '1', '1'],
['0', '1', '1', '1'],
],
},
output: 9,
},
])('input: matrix = $input.matrix', ({ input: { matrix }, output }) => {
expect(maximalSquare(matrix)).toEqual(output)
})