Count Square Submatrices with All Ones

Medium Topics Company Tags

Count the square submatrices of matrix whose entries are all 1. Each square must use consecutive rows and consecutive columns, with the same number of each. Squares of side length 1 count, and overlapping squares are counted separately. Return the total across all positions and sizes.

Example 1:

Input: matrix = [[1,1],[1,1]]

Output: 5

Explanation: Each of the four cells forms a square of side length 1, and the entire matrix forms one square of side length 2. The total is 5.

Example 2:

Input: matrix = [[1,0,1]]

Output: 2

Explanation: Only the first and last cells contain 1. Each counts as a separate square, and a single-row matrix cannot contain a larger square.

Example 3:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]

Output: 8

Explanation: The eight cells containing 1 each contribute one square. Every possible larger square includes the central 0, so none of them qualifies.

Constraints:

  • 1 <= matrix.length <= 300
  • 1 <= matrix[i].length <= 300
  • All rows have the same length.
  • Each entry is 0 or 1.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.