oneby7

2-D Dynamic Programming Paths in a grid

544. Count Square Submatrices with All Ones

Medium

You are given a grid matrix with m rows and n columns, in which every cell holds 0 or 1. Return the number of square blocks of cells that hold only 1s.

A square block is a run of k neighbouring rows and, in each of them, the same run of k neighbouring columns, for any k from 1 up. A single cell that holds 1 is a square of side 1. Squares may overlap, and every square counts once, so two squares are different if they differ in position or in size.

Example 1

1110111101111111

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

Output: 21

Explanation: There are 14 squares of side 1, one for each 1, and 6 squares of side 2. The one square of side 3 covers rows 1 to 3 and columns 1 to 3. That makes 14 + 6 + 1 = 21.

Example 2

111111111

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

Output: 14

Explanation: The grid holds 9 squares of side 1, 4 of side 2 and the whole grid as one square of side 3. The four squares of side 2 overlap, and each one counts.

Example 3

000000

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

Output: 0

Explanation: There is no 1, so there is no square of 1s.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[1, 1], [1, 1], [1, 1]]

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 ≤ m, n ≤ 105
  • 1 ≤ m · n ≤ 105
  • matrix[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.