Skip to content

Commit 87c3ecf

Browse files
authored
Create matrix-block-sum.py
1 parent c25d531 commit 87c3ecf

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Python/matrix-block-sum.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Time: O(m * n)
2+
# Space: O(m * n)
3+
4+
class Solution(object):
5+
def matrixBlockSum(self, mat, K):
6+
"""
7+
:type mat: List[List[int]]
8+
:type K: int
9+
:rtype: List[List[int]]
10+
"""
11+
m, n = len(mat), len(mat[0])
12+
accu = [[0 for _ in xrange(n+1)] for _ in xrange(m+1)]
13+
for i in xrange(m):
14+
for j in xrange(n):
15+
accu[i+1][j+1] = accu[i+1][j]+accu[i][j+1]-accu[i][j]+mat[i][j]
16+
result = [[0 for _ in xrange(n)] for _ in xrange(m)]
17+
for i in xrange(m):
18+
for j in xrange(n):
19+
r1, c1, r2, c2 = max(i-K, 0), max(j-K, 0), min(i+K+1, m), min(j+K+1, n)
20+
result[i][j] = accu[r2][c2]-accu[r1][c2]-accu[r2][c1]+accu[r1][c1]
21+
return result

0 commit comments

Comments
 (0)