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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defcountSquares(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 == 0or 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: