Skip to content

Commit c73e11f

Browse files
authored
Create 1074-number-of-submatrices-that-sum-to-target.kt
1 parent 95f5f74 commit c73e11f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
fun numSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int {
3+
val n = matrix.size
4+
val m = matrix[0].size
5+
val prefix = Array (n) { IntArray (m) }
6+
7+
for (i in 0 until n) {
8+
for (j in 0 until m) {
9+
val top = if (i > 0) prefix[i - 1][j] else 0
10+
val left = if (j > 0) prefix[i][j - 1] else 0
11+
val topLeft = if (minOf(i, j) > 0) prefix[i - 1][j - 1] else 0
12+
prefix[i][j] = matrix[i][j] + top + left - topLeft
13+
}
14+
}
15+
16+
var res = 0
17+
for (i in 0 until n) {
18+
for (i2 in i until n) {
19+
var count = HashMap<Int, Int>()
20+
count[0] = 1
21+
for (j in 0 until m) {
22+
val curSum = prefix[i2][j] - (if (i > 0) prefix[i - 1][j] else 0)
23+
val diff = curSum - target
24+
res += (count[diff] ?: 0)
25+
count[curSum] = (count[curSum] ?: 0) + 1
26+
}
27+
}
28+
}
29+
30+
return res
31+
}
32+
}

0 commit comments

Comments
 (0)