2-D Dynamic Programming Paths in a grid
544. Count Square Submatrices with All Ones
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
Input: matrix = [[1, 1, 1, 0],
[1, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1]]
21Explanation: 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
Input: matrix = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
14Explanation: 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
Input: matrix = [[0, 0, 0], [0, 0, 0]]
0Explanation: 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.
Constraints
m == matrix.length,n == matrix[i].length1 ≤ m, n ≤ 1051 ≤ m · n ≤ 105matrix[i][j]is 0 or 1.
Clarifying questions
What you would ask an interviewer before writing any code.