Problem description:

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
Input: matrix =
[
  [0,1,1,1],
  [1,1,1,1],
  [0,1,1,1]
]
Output: 15
Explanation:
There are10 squares of side 1.
There are4 squares of side 2.
There is1 square of side 3.
Total number of squares = 10 + 4 + 1 =15.

Example 2:

1
2
3
4
5
6
7
8
9
10
11
Input: matrix =
[
[1,0,1],
[1,1,0],
[1,1,0]
]
Output: 7
Explanation:
There are6 squares of side 1.
There is1 square of side 2.
Total number of squares = 6 + 1 =7.

Constraints:

  • 1 <= arr.length <= 300
  • 1 <= arr[0].length <= 300
  • 0 <= arr[i][j] <= 1

Solution:

https://assets.leetcode.com/users/arkaung/image_1590051166.png

https://assets.leetcode.com/users/arkaung/image_1590051442.png

https://assets.leetcode.com/users/arkaung/image_1590051171.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
# all squares could build on matrix[i][j]
# rely on matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1]
m, n = len(matrix), len(matrix[0])
res = 0
for i in range(m):
for j in range(n):
if matrix[i][j]:
if i == 0 or j == 0:
res += 1
else:
matrix[i][j] = min(matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1])+matrix[i][j]
res += matrix[i][j]
return res

time complexity: $O()$
space complexity: $O()$
reference:
related problem: