2
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:3
m, n = len(matrix), len(matrix[0])4
matrix_sums = [[0 for _ in range(n)] for _ in range(m)]6
# Calculate all the submatrices sum with the transition formula we found10
if row == 0 and col == 0:11
matrix_sums[row][col] = matrix[row][col]12
# Rows and columns are like prefix sums, without intersection14
matrix_sums[row][col] = matrix[row][col] + matrix_sums[row][col - 1]16
matrix_sums[row][col] = matrix[row][col] + matrix_sums[row - 1][col]18
# current sum is the sum of the matrix above, to the left and subtract the intersection20
matrix_sums[row][col] = (22
+ (matrix_sums[row][col - 1])23
+ (matrix_sums[row - 1][col])24
- (matrix_sums[row - 1][col - 1])28
# Generate all submatrices31
for y2 in range(y1, m):32
for x2 in range(x1, n):33
# calculate sum in O(1)36
- (matrix_sums[y2][x1 - 1] if x1 - 1 >= 0 else 0)37
- (matrix_sums[y1 - 1][x2] if y1 - 1 >= 0 else 0)39
matrix_sums[y1 - 1][x1 - 1]40
if y1 - 1 >= 0 and x1 - 1 >= 045
if submatrix_total == target: