Sub topic 12
Maximal Square of Ones
This chapter assumes you can already write a grid recurrence, add a row and column of padding to handle edges, and fill a table row by row. Earlier chapters on minimum-cost paths and boundary handling cover those skills. The problem is this: given a binary matrix of '1' and '0' characters, find the area of the largest square that contains only ones.
Choosing a State That Composes
You might first try to define the state as "the largest square anywhere in the top-left i × j region." That definition does not combine well. Knowing the best square so far tells you nothing about whether the current cell extends it.
A better state fixes where the square ends:
dp[i][j]is the side length of the largest all-ones square whose bottom-right corner is cell(i, j).
Now a cell's value depends only on squares that touch it, and the global answer is the maximum over all cells.
Why the Recurrence Uses `min`
Suppose cell (i, j) holds a one, and you want a square of side k to end there. Three smaller squares of side k - 1 must then exist, ending at these cells:
- the cell above,
(i-1, j) - the cell to the left,
(i, j-1) - the cell diagonally up-left,
(i-1, j-1)
These three squares overlap and together cover the big square, except for the corner cell itself. The shortest of the three limits how far the square can grow:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) when the cell is '1', and 0 otherwise.
All three dependencies sit above or to the left of the current cell, so a normal row-major fill computes them before you need them.
Implementation
def maximal_square(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], dp[i][j - 1], dp[i - 1][j - 1])
best = max(best, dp[i][j])
return best * best
print(maximal_square([['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']])) # 4The padding row and column hold zeros. That means cells on the top row or left column can still read three neighbors without index checks, and the recurrence correctly gives them a value of at most 1.
Tracing the Example
Here is the filled table without the padding:
| row | c0 | c1 | c2 | c3 | c4 |
|---|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 | 0 |
| 1 | 1 | 0 | 1 | 1 | 1 |
| 2 | 1 | 1 | 1 | 2 | 2 |
| 3 | 1 | 0 | 0 | 1 | 0 |
The largest value is 2, so the area is 4. Look at row 2, column 4. Its neighbors are 1 (above), 2 (left), and 1 (diagonal). The minimum is 1, so the value is 2. The left neighbor could support a bigger square, but the other two cannot.
Common Errors
- Comparing to the wrong type. Inputs often store the string
'1', so== 1silently fails on every cell. Match the input's actual type. - Using
maxinstead ofmin. A square can only grow as far as its weakest supporting neighbor allows. - Forgetting the diagonal. If you check only the cell above and the cell to the left, you can miss a zero in the up-left corner.
Time is O(mn) and space is O(mn). You can reduce space to O(n) with the rolling-array technique from the earlier chapter. The diagonal value gets overwritten during the row pass, so save it in a temporary variable before you update each cell.
Exercise
How would you change maximal_square so that it returns the total number of all-ones square submatrices of any size, instead of the largest area?
Show answer
Replace the running maximum with a running sum: add dp[i][j] to a total for every cell, and return the total. A cell with dp[i][j] = k is the bottom-right corner of exactly k all-ones squares, one each of sides 1 through k.
Exercise
For matrix [['1','1','1'],['1','1','1'],['1','1','0']], what is dp at the bottom-right cell, and what does the function return?
Show answer
The bottom-right cell is '0', so its dp value is 0. The largest value elsewhere is 2 (for example at row 1, column 1, or at row 1, column 2), so the function returns 4.