All problems
0355MediumArrayDynamic ProgrammingMatrix

Largest Intact Mosaic Square

Tracked in this browser only
Write code

Trains the technique from

LeetCode 221Maximal Square

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A mosaic panel is surveyed tile by tile into matrix. Each entry is the one-character string "1" when that tile is intact or "0" when it is cracked.

A restorer wants to cut out the largest square block of tiles that contains no cracked tile. The block must be aligned with the grid and every tile inside it must be intact.

Return the number of tiles such a largest square block covers, or 0 when every tile is cracked.

Examples

Example 1

Input
matrix = [["1","0","1","1"],["1","1","1","1"],["0","1","1","1"]]
Output
4

The tiles in rows 1 and 2 across columns 2 and 3 are all intact, giving a 2 by 2 block that covers 4 tiles. No 3 by 3 block is free of cracks.

Example 2

Input
matrix = [["0","1"],["1","1"]]
Output
1

Three tiles are intact but they do not form a 2 by 2 block, so the best square is a single tile covering 1 tile.

Example 3

Input
matrix = [["0","0"],["0","0"]]
Output
0

Every tile is cracked, so no square block can be cut at all.

Constraints

  • m == matrix.length
  • n == matrix[r].length
  • 1 <= m, n <= 300
  • matrix[r][c] is "0" or "1".

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def maximal_square(matrix: list[list[str]]) -> int:
Java
public int maximalSquare(char[][] matrix)
September 7
Apply