#1277

Count Square Submatrices with All Ones

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n^3)
O(m * n)
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal approach uses dynamic programming to build a table that keeps track of the size of the largest square submatrix ending at each cell. This allows us to calculate the total count efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table of the same size as the input matrix initialized to zero.
  2. 2Step 2: Iterate through each cell in the matrix. If the cell is 1, update the DP table based on the minimum of the three neighboring cells (top, left, top-left diagonal).
  3. 3Step 3: Sum the values in the DP table to get the total count of square submatrices.
solution.py17 lines
1# Full working Python code
2
3def countSquares(matrix):
4    if not matrix:
5        return 0
6    count = 0
7    m, n = len(matrix), len(matrix[0])
8    dp = [[0] * n for _ in range(m)]
9    for i in range(m):
10        for j in range(n):
11            if matrix[i][j] == 1:
12                dp[i][j] = 1
13                if i > 0 and j > 0:
14                    dp[i][j] += min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
15                count += dp[i][j]
16    return count
17

Complexity note: The complexity is O(m * n) because we iterate through each cell once and perform constant time operations for each cell.

  • 1Dynamic programming allows us to build solutions incrementally, reducing redundant checks.
  • 2Understanding how to relate subproblems is crucial for optimizing solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.