class Solution:
def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
m,n = len(mat),len(mat[0])
sum = [[0]*(n+1) for _ in range(m+1)]
for i in range(m):
for j in range(n):
sum[i+1][j+1] = mat[i][j] - sum[i][j] + sum[i][j+1] + sum[i+1][j]
result = [[0]*n for _ in range(m)]
for i in range(m):
for j in range(n):
r1, c1, r2, c2 = max(0, i - K), max(0, j - K), min(m, i + K + 1), min(n, j + K + 1)
result[i][j] = sum[r1][c1]+sum[r2][c2]-sum[r1][c2]-sum[r2][c1]
return result
C++
Java
Python
C
C
JavaScript
Ruby
Swift
Go
Scala
Kotlin
Rust
PHP