CodingNodes / 2-D Dynamic Programming / Maximal Square System design Space play · ←→ step · R restart

Problem

A grid matrix is filled with the characters "0" and "1". Find the largest square made up only of "1" cells, and return its area (side length times side length). If the grid has no "1", return 0.

Constraints

  • 1 ≤ rows, columns ≤ 300
  • every cell is the character "0" or "1"

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(m · n)

Time: Each of the m · n cells is visited once and costs a constant number of lookups.

Space: The dp table has (m + 1) · (n + 1) cells.

Let dp[i][j] be the side of the largest all-1 square whose bottom right corner is that cell. A 0 cell gives 0. A 1 cell extends the smallest of its three neighbours (above, left, up-left) by one, because a bigger square needs all three smaller squares to exist. Track the best side and square it at the end.