-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix-block-sum.py
32 lines (29 loc) · 970 Bytes
/
matrix-block-sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# https://leetcode.com/problems/matrix-block-sum/
from typing import List
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
result = []
m = len(mat)
n = len(mat[0])
for i in range(m):
row = []
for j in range(n):
rowStart = i - k
colStart = j - k
if rowStart < 0:
rowStart = 0
if colStart < 0:
colStart = 0
rowEnd = i + k
colEnd = j + k
if rowEnd >= m:
rowEnd = m - 1
if colEnd >= n:
colEnd = n - 1
c = 0
for ii in range(rowStart, rowEnd + 1):
for jj in range(colStart, colEnd + 1):
c += mat[ii][jj]
row.append(c)
result.append(row)
return result