02
Squares and shapes (DP — Grid Sub-pattern)
dp[r][c] = the biggest shape with its corner at (r, c). For squares: 1 + min(top, left, top-left) on a 1-cell, 0 on a 0-cell.
Signals in the problem statement
- ›
"largest square of 1s"
- ›
"count square submatrices with all ones"
- ›
a matrix of 0s and 1s
What makes it different
The answer is not in the corner cell — it is the max (largest square) or the sum (count of squares) over all cells.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Maximal SquareWalkthroughMediumBasic Anchor·LeetCode #221
- 2Count Square Submatrices with All OnesWalkthroughMediumBasic Reinforcement·LeetCode #1277
Template
square-template.cpp
// dp[c + 1] (current row) = side of the largest all-1 square whose bottom-right corner is (r, c).
// It is 1 + min(top, left, top-left); top-left is saved in `diag` before it is overwritten.
int largestSquareSide(const vector<vector<char>>& g) {
int m = g.size(), n = g[0].size(), best = 0;
vector<int> dp(n + 1, 0); // dp[c + 1] is column c; dp[0] stays 0
for (int r = 0; r < m; r++) {
int diag = 0; // top-left of the cell being filled
for (int c = 0; c < n; c++) {
int top = dp[c + 1]; // still the previous row's value
dp[c + 1] = g[r][c] == '1' ? 1 + min({top, dp[c], diag}) : 0;
diag = top;
best = max(best, dp[c + 1]); // sum dp[c + 1] instead to COUNT squares
}
}
return best; // the area is best * best
}Remember this · DP — Grid
Trigger
Move only right/down, count paths, minimum path cost, largest square of 1s.
Think
To reach cell (r, c), which cells could I have come from?
Key question
What does dp[r][c] mean, and what are the first row/column?