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.

2 variations · 3 problems · 3 with animated walkthroughs

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

Squares
// 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;
}

The variations

  1. 1The square ending at this cell

    A square of side s ends at (r, c) only if squares of side s - 1 end above, to the left and diagonally. So dp = 1 + min(up, left, diagonal). The max of dp is the largest square; the sum of dp counts every square, because side s contains squares of sides 1 to s ending here.

  2. 2Only the border matters

    Precompute how many 1s run left and up from every cell. A cell with both runs at least s gives 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.
Next: State machine DP: every Buy and Sell Stock problem →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.