Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 0583db9

Browse files
committed
1074 improved
1 parent 0ec16f2 commit 0583db9

File tree

2 files changed

+123
-17
lines changed

2 files changed

+123
-17
lines changed

Algorithms/1074.number-of-submatrices-that-sum-to-target/number-of-submatrices-that-sum-to-target.go

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,27 @@
11
package problem1074
22

3-
func numSubmatrixSumTarget(M [][]int, target int) int {
4-
m, n := len(M), len(M[0])
3+
func numSubmatrixSumTarget(A [][]int, target int) int {
4+
m, n := len(A), len(A[0])
55

6-
sums := [301][301]int{}
7-
for i := 1; i <= m; i++ {
8-
t := 0
9-
for j := 1; j <= n; j++ {
10-
t += M[i-1][j-1]
11-
sums[i][j] = t + sums[i-1][j]
6+
for i := 0; i < m; i++ {
7+
for j := 1; j < n; j++ {
8+
A[i][j] += A[i][j-1]
129
}
1310
}
1411

1512
res := 0
16-
17-
for x1 := 0; x1 < m; x1++ {
18-
for x2 := x1 + 1; x2 <= m; x2++ {
19-
for y1 := 0; y1 < n; y1++ {
20-
for y2 := y1 + 1; y2 <= n; y2++ {
21-
s := sums[x2][y2] - sums[x1][y2] - sums[x2][y1] + sums[x1][y1]
22-
if s == target {
23-
res++
24-
}
13+
for y1 := 0; y1 < n; y1++ {
14+
for y2 := y1; y2 < n; y2++ {
15+
count := make(map[int]int, n)
16+
count[0] = 1
17+
cur := 0
18+
for x := 0; x < m; x++ {
19+
cur += A[x][y2]
20+
if y1-1 >= 0 {
21+
cur -= A[x][y1-1]
2522
}
23+
res += count[cur-target]
24+
count[cur]++
2625
}
2726
}
2827
}

0 commit comments

Comments
 (0)