Skip to content

Commit aaff954

Browse files
authored
Create 1074-number-of-submatrices-that-sum-to-target.py
1 parent c73e11f commit aaff954

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
3+
ROWS, COLS = len(matrix), len(matrix[0])
4+
sub_sum = [[0 for i in range(COLS)] for j in range(ROWS)]
5+
6+
for r in range(ROWS):
7+
for c in range(COLS):
8+
top = sub_sum[r - 1][c] if r > 0 else 0
9+
left = sub_sum[r][c - 1] if c > 0 else 0
10+
top_left = sub_sum[r - 1][c - 1] if min(r, c) > 0 else 0
11+
sub_sum[r][c] = matrix[r][c] + top + left - top_left
12+
13+
res = 0
14+
for r1 in range(ROWS):
15+
for r2 in range(r1, ROWS):
16+
count = defaultdict(int) # prefix_sum -> count
17+
count[0] = 1
18+
for c in range(COLS):
19+
cur_sum = sub_sum[r2][c] - (
20+
sub_sum[r1 - 1][c] if r1 > 0 else 0
21+
)
22+
diff = cur_sum - target
23+
res += count[diff]
24+
count[cur_sum] += 1
25+
26+
return res

0 commit comments

Comments
 (0)