File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments