KatInterview

Biggest Solid Block in a Binary Grid

Dynamic ProgrammingAuto-graded · 19 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingmatrixspace-optimization

Last updated

Find the area of the largest square made only of '1' cells in a grid of character digits, using a dynamic programming recurrence that can be compressed to a single row of state.

Biggest Solid Block in a Binary Grid

You are given a rectangular grid with m rows and n columns. Each cell holds a single-character string, either "0" or "1".

A solid block is a square sub-grid, with sides aligned to the rows and columns, in which every cell is "1". Find the largest solid block and return its area, that is, the number of cells it contains.

If the grid contains no "1" at all, return 0.

Aim for O(m * n) time and no more than O(n) additional memory beyond the input.

Input

  • grid: a list of m lists, each with n strings. Each string is exactly "0" or "1".

Output

  • An integer: the area (side length squared) of the largest square consisting only of "1" cells.

Notes

  • The cell values are characters, not integers, so compare them with "1".
  • Return the area, not the side length.
  • A grid with a single row or a single column can only have blocks of side 1 at most.

Constraints

  • 1 <= m, n <= 300
  • grid[i][j] is either "0" or "1".
  • All rows have the same length.

Examples

Example 1

Input: largest_solid_block([['1', '0', '1', '0', '0'], ['1', '0', '1', '1', '1'], ['1', '1', '1', '1', '1'], ['1', '0', '0', '1', '0']])

Output: 4

Example 2

Input: largest_solid_block([['0', '1'], ['1', '0']])

Output: 1

Example 3

Input: largest_solid_block([['0']])

Output: 0

Hints

Hint 1

For each cell, ask: what is the side of the largest all-ones square whose bottom-right corner is exactly this cell? Every square has exactly one such corner.

Hint 2

If the cell is '1', that side equals 1 + the minimum of the answers for the cell above, the cell to the left, and the cell diagonally up-left. If it is '0', the answer is 0.

Hint 3

Each row only depends on the previous row and on the cells already computed in the current row. Keep one array, and save the old value of the cell you are about to overwrite, because it becomes the diagonal value for the next column.