Given a matrix filled with 0s and 1s, find the largest square whose cells are all 1, and return its area. This is LeetCode 221, a classic warm-up for two-dimensional dynamic programming: the answer for each cell turns out to depend on the answers already computed for a few of its neighbours. The squares must be axis-aligned (no rotated diamonds), and if the matrix is empty the area is 0.
maximalSquare(matrix) // 2D array of 0/1 -> area of the largest all-1 square
matrix is a rectangular 2D array of numbers 0 and 1. Return a single number: the area (side length squared), not the side length.
maximalSquare([
[1, 0, 1, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 1, 0],
]); // 4 — the biggest all-1 square is 2x2, so area = 2 * 2
maximalSquare([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
]); // 9 — the whole grid is one 3x3 square
maximalSquare([
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
]); // 1 — the single 0 in the middle blocks any square bigger than 1x1
0 or 1. Cells with a "0"/"1" string are coerced with Number(), so both forms work.4, a 3x3 returns 9.1s is not a square.[]) or a matrix with no columns ([[]]) has area 0.