Dynamic Programming · Pattern 5 of 12
Squares: the largest square ending at each cell
dp[r][c] = side of the largest all-ones square whose bottom-right corner is (r, c). It is one more than the smallest of its three neighbours: up, left and up-left.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Largest square of 1s in a binary matrix
- Count all square submatrices made of 1s
- A square whose border (not its inside) must be all 1s
The template
// dp[r][c] = side of the largest all-ones square with bottom-right corner (r - 1, c - 1)
int countSquares(int[][] m) {
int rows = m.length, cols = m[0].length, total = 0;
int[][] dp = new int[rows + 1][cols + 1]; // a border of zeros removes edge checks
for (int r = 1; r <= rows; r++)
for (int c = 1; c <= cols; c++)
if (m[r - 1][c - 1] == 1) {
dp[r][c] = 1 + Math.min(dp[r - 1][c - 1], Math.min(dp[r - 1][c], dp[r][c - 1]));
total += dp[r][c]; // side s means s squares end here (Maximal Square: take the max)
}
return total;
}
// Largest 1-Bordered Square: runs of 1s to the left and upwards from each cell
int largest1BorderedSquare(int[][] g) {
int rows = g.length, cols = g[0].length, best = 0;
int[][] left = new int[rows + 1][cols + 1], up = new int[rows + 1][cols + 1];
for (int r = 1; r <= rows; r++)
for (int c = 1; c <= cols; c++) {
if (g[r - 1][c - 1] == 0) continue;
left[r][c] = left[r][c - 1] + 1;
up[r][c] = up[r - 1][c] + 1;
// bottom and right edges come from this cell; check the top and left edges
for (int s = Math.min(left[r][c], up[r][c]); s > best; s--)
if (up[r][c - s + 1] >= s && left[r - s + 1][c] >= s) { best = s; break; }
}
return best * best;
} def count_squares(m):
rows, cols = len(m), len(m[0])
dp = [[0] * (cols + 1) for _ in range(rows + 1)] # a border of zeros removes edge checks
total = 0
for r in range(1, rows + 1):
for c in range(1, cols + 1):
if m[r - 1][c - 1] == 1:
dp[r][c] = 1 + min(dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1])
total += dp[r][c] # side s means s squares end here (Maximal Square: take the max)
return total
def largest1_bordered_square(g):
rows, cols = len(g), len(g[0])
left = [[0] * (cols + 1) for _ in range(rows + 1)]
up = [[0] * (cols + 1) for _ in range(rows + 1)]
best = 0
for r in range(1, rows + 1):
for c in range(1, cols + 1):
if g[r - 1][c - 1] == 0:
continue
left[r][c] = left[r][c - 1] + 1
up[r][c] = up[r - 1][c] + 1
for s in range(min(left[r][c], up[r][c]), best, -1): # top and left edges
if up[r][c - s + 1] >= s and left[r - s + 1][c] >= s:
best = s
break
return best * best // dp[r][c] = side of the largest all-ones square with bottom-right corner (r - 1, c - 1)
int countSquares(vector<vector<int>>& m) {
int rows = m.size(), cols = m[0].size(), total = 0;
vector<vector<int>> dp(rows + 1, vector<int>(cols + 1, 0));
for (int r = 1; r <= rows; r++)
for (int c = 1; c <= cols; c++)
if (m[r - 1][c - 1] == 1) {
dp[r][c] = 1 + min({dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1]});
total += dp[r][c]; // side s means s squares end here (Maximal Square: take the max)
}
return total;
}
// Largest 1-Bordered Square: runs of 1s to the left and upwards from each cell
int largest1BorderedSquare(vector<vector<int>>& g) {
int rows = g.size(), cols = g[0].size(), best = 0;
vector<vector<int>> left(rows + 1, vector<int>(cols + 1, 0)), up = left;
for (int r = 1; r <= rows; r++)
for (int c = 1; c <= cols; c++) {
if (g[r - 1][c - 1] == 0) continue;
left[r][c] = left[r][c - 1] + 1;
up[r][c] = up[r - 1][c] + 1;
for (int s = min(left[r][c], up[r][c]); s > best; s--) // top and left edges
if (up[r][c - s + 1] >= s && left[r - s + 1][c] >= s) { best = s; break; }
}
return best * best;
} // dp[r][c] = side of the largest all-ones square with bottom-right corner (r - 1, c - 1)
function countSquares(m) {
const rows = m.length, cols = m[0].length;
const dp = Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0));
let total = 0;
for (let r = 1; r <= rows; r++)
for (let c = 1; c <= cols; c++)
if (m[r - 1][c - 1] === 1) {
dp[r][c] = 1 + Math.min(dp[r - 1][c - 1], dp[r - 1][c], dp[r][c - 1]);
total += dp[r][c]; // side s means s squares end here (Maximal Square: take the max)
}
return total;
}
// Largest 1-Bordered Square: runs of 1s to the left and upwards from each cell
function largest1BorderedSquare(g) {
const rows = g.length, cols = g[0].length;
const grid = () => Array.from({ length: rows + 1 }, () => new Array(cols + 1).fill(0));
const left = grid(), up = grid();
let best = 0;
for (let r = 1; r <= rows; r++)
for (let c = 1; c <= cols; c++) {
if (g[r - 1][c - 1] === 0) continue;
left[r][c] = left[r][c - 1] + 1;
up[r][c] = up[r - 1][c] + 1;
for (let s = Math.min(left[r][c], up[r][c]); s > best; s--) // top and left edges
if (up[r][c - s + 1] >= s && left[r - s + 1][c] >= s) { best = s; break; }
}
return best * best;
} The variations
-
1The square ending at this cell
A square of side
sends at(r, c)only if squares of sides - 1end above, to the left and diagonally. Sodp = 1 + min(up, left, diagonal). The max ofdpis the largest square; the sum ofdpcounts every square, because sidescontains squares of sides 1 tosending here.Now you solve -
2Only the border matters
Precompute how many 1s run left and up from every cell. A cell with both runs at least
sgives the bottom and right edges; then check the run up from the bottom-left corner and the run left from the top-right corner.
Mistakes to avoid
- Maximal Square asks for the area: return
side * side, not the side. - In Maximal Square the matrix holds the characters
'0'and'1', not numbers. - For bordered squares, using the min-of-three rule: the inside may contain zeros, so you need run lengths instead.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.