Find the biggest square of 1s in a grid. For each cell, the largest square ending there is one more than the smallest of the squares above, to the left and diagonally up-left, so one pass fills the table in O(mn).
▼The problem
LeetCode 221 (Medium). Given an m × n binary matrix of "0"s and "1"s, return the area of the largest square that contains only 1s.
Examples (LeetCode's): [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] → 4, [["0","1"],["1","0"]] → 1 and [["0"]] → 0.
The solution
def maximalSquare(matrix):
m, n = len(matrix), len(matrix[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
best = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if matrix[i - 1][j - 1] == "1":
dp[i][j] = 1 + min(dp[i - 1][j], # up
dp[i][j - 1], # left
dp[i - 1][j - 1]) # diagonal
best = max(best, dp[i][j])
return best * bestTranscript
Maximal Square. Picture a solar farm as a grid. A one is a working panel, a zero is a broken one. Find the largest square made only of working panels, and return its area.
Here's a field with four rows and five columns. A two by two block of working panels fits, so the answer is four. A three by three never fits: every try hits a broken panel.
The slow way tries every panel as a top-left corner and grows a square, rechecking every panel inside at each step. This small field takes sixty-five checks. A twenty by twenty field of working panels takes over a hundred thousand.
Instead, give each panel one number: the side of the largest square whose bottom-right corner is that panel. A broken panel gets zero. A working one looks up, left, and diagonally up-left, and takes one plus their minimum.
Why the minimum? A three by three here needs a two by two ending at each neighbor. Together, they cover everything but the corner. But the diagonal only reaches one: a broken panel leaves a hole. So this corner gets one plus one: two.
Let's fill the field row by row. The top row and left column copy the panels. In row two, every working panel touches a zero, so each stays one. In row three, column four sees one, one, one, and becomes two. Its neighbor sees one, two, one: the minimum holds it at two. The largest value is two, so the area is four.
In code, pad the table with a row and column of zeros, so edges need no special case. For every working panel, store one plus the minimum of up, left and diagonal, and keep the largest side. Return it squared.
Each panel costs three lookups and a minimum, so the time is order m times n. The table takes m times n space, but each row only reads the row above, so one row is enough: order n.
Look up, left and diagonally, take the smallest, add one. That's Maximal Square.