Count Square Submatrices with All Ones Problem
Description
LeetCode Problem 1277.
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example 1:
Input: matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is 1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.
Example 2:
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.
Constraints:
1 <= arr.length <= 3001 <= arr[0].length <= 3000 <= arr[i][j] <= 1
Solution
Approach: Dynamic Programming on the Bottom-Right Corner
Let side[i][j] be the side of the largest all-ones square whose bottom-right corner is (i, j). That one value tells us how many squares end there: if the largest has side s, then the squares of sides 1, 2, ..., s with this corner are all made of ones, and no larger one is. So the answer is the sum of side[i][j] over all cells.
To compute it:
- If
matrix[i][j] == 0, thenside[i][j] = 0. - If the cell is
1in the first row or column, thenside[i][j] = 1. - Otherwise
side[i][j] = min(side[i-1][j], side[i][j-1], side[i-1][j-1]) + 1.
Why the minimum of the three neighbours? A square of side s ending at (i, j) contains squares of side s - 1 ending at the cell above, the cell to the left and the cell up-left. Conversely, if all three of those have squares of side s - 1, together with (i, j) they cover a full square of side s. So the weakest of the three limits the square.
For the first example, the cells hold 0 1 1 1 / 1 1 2 2 / 0 1 2 3, which add up to 15.
Complexity: O(m·n) time and O(m·n) space for an m x n matrix (one row of side at a time would also be enough).
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
side = [[0] * n for _ in range(m)] # largest all-ones square with (i, j) as bottom-right corner
total = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == 0:
continue
if i == 0 or j == 0:
side[i][j] = 1
else:
side[i][j] = min(side[i - 1][j], side[i][j - 1], side[i - 1][j - 1]) + 1
total += side[i][j] # squares of sides 1..side[i][j] end here
return total