sagelearnai

Count Square Submatrices with All Ones

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #1277

Given an m × n matrix of 0s and 1s, return how many square submatrices consist entirely of ones.

Examples

text
[[0,1,1,1],
 [1,1,1,1],
 [0,1,1,1]]  →  15   (10 of size 1, 4 of size 2, 1 of size 3)
[[1,0,1],[1,1,0],[1,1,0]]  →  7

Hints

  1. dp[r][c] = the side of the largest all-ones square ending at (r, c). How many squares end at (r, c)?

Approach

If the largest square with bottom-right corner (r,c) has side k, then exactly k squares end there (sides 1..k). So the answer is Σ dp[r][c] using the Maximal Square recurrence 1 + min(top, left, diag). Computing in place over the input matrix gives O(1) extra space.

Complexity

Time: O(m·n). Space: O(m·n) here (O(1) in place).

Python solution
def countSquares(matrix):
    R, C = len(matrix), len(matrix[0])
    dp = [row[:] for row in matrix]
    total = 0
    for r in range(R):
        for c in range(C):
            if dp[r][c] and r and c:
                dp[r][c] = 1 + min(dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1])
            total += dp[r][c]
    return total
JavaScript solution
function countSquares(matrix) {
  const dp = matrix.map((r) => [...r]);
  let total = 0;
  for (let r = 0; r < dp.length; r++) for (let c = 0; c < dp[0].length; c++) {
    if (dp[r][c] && r && c) dp[r][c] = 1 + Math.min(dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]);
    total += dp[r][c];
  }
  return total;
}