Skip to problem
←

Count Square Submatrices with All Ones

Medium 0 attempts

You're given a binary matrix of size m×n. Count every square-shaped submatrix, of any size, whose cells are entirely ones, and return the total count.

Function contract

Implement countSquares(matrix), where matrix is a non-empty rectangular binary grid.

Output: The total number of contiguous square submatrices containing only 1s, counting every position and side length separately.

Example 1

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

Explanation: There are ten 1×1 squares, four 2×2 squares, and one 3×3 square: 10 + 4 + 1 = 15.

Example 2

Input
matrix = [[0]]
Output
0
Visual Aid
Different sizes count separately
1111Four 1×1 + one 2×2 = 5 squares

Overlapping squares are counted independently; this is not a partition of the grid.

Constraints
  • 1 <= m, n <= 300
  • matrix[i][j] is 0 or 1

DP

The value at (i, j) becomes the side length of the largest all-one square whose bottom-right corner is (i, j). If that length is k, exactly k squares of sizes 1 through k end there. Sum those lengths. This implementation overwrites the input matrix to store DP values.

javascript
function countSquares(matrix) {
  const m = matrix.length, n = matrix[0].length;
  let count = 0;
  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      if (matrix[i][j] && i > 0 && j > 0) {
        matrix[i][j] = Math.min(matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1]) + 1;
      }
      count += matrix[i][j];
    }
  }
  return count;
}

Time: O(mn) | Space: O(1) auxiliary space, reusing the input matrix.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript