Maximal Square
Master this topic with zero to advance depth.
Maximal Square
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Visual Representation
Matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
The 2x2 square of 1s at (1,2) to (2,3) is one of the squares.
Wait, there is a larger one? No, area is 4.
DP Strategy:
dp[i][j] = side length of the largest square ending at (i, j).Examples
Level I: Dynamic Programming (2D)
Intuition
A square of size k ending at (i, j) can only be formed if there are squares of size k-1 ending at (i-1, j), (i, j-1), and (i-1, j-1).
Thought Process
dp[i][j]represents the side length of the largest square ending atmatrix[i][j].- If
matrix[i][j] == '1':dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1.
- Keep track of the maximum side length found so far.
- Result =
maxSide * maxSide.
Detailed Dry Run
Matrix: 1 1 1 1
| i\j | 0 | 1 |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 1 | min(1, 1, 1)+1 = 2 |
| Result: 2^2 = 4 |
Level II: Memoization (Top-Down)
Intuition
Cache the result of dp(i, j) so each cell is computed only once. The recurrence: dp(i,j) = min(dp(i-1,j), dp(i,j-1), dp(i-1,j-1)) + 1 if matrix[i][j]=='1'.
Visual
Matrix: Memo:
1 1 1 1 1 1
1 1 1 -> 1 2 ?
1 1 1 1 ? 3 <- dp(2,2) = min(2,2,2)+1=3Detailed Dry Run
dp(2,2): matrix[2][2]='1'. min(dp(1,2)=2, dp(2,1)=2, dp(1,1)=2)+1=3. Area=9.
Level III: Space Optimized (1D)
Intuition
We only need the previous row and the current row. Specifically, dp[i-1][j], dp[i][j-1], and the diagonal dp[i-1][j-1].
Logic Steps
- Initialize a
dparray of sizen + 1. - Use a
prevvariable to store the diagonal valuedp[i-1][j-1]from the previous row. - Iterate row by row.
Detailed Dry Run
Same logic as 2D but overwriting the same row array. 'prev' variable caches the upper-left (diagonal) value before it gets updated for the current row's calculation.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.