35 lines
1.2 KiB
Plaintext
35 lines
1.2 KiB
Plaintext
|
class Solution {
|
||
|
public int numSubmatrixSumTarget(int[][] matrix, int target) {
|
||
|
int xLength = matrix.length;
|
||
|
int yLength = matrix[0].length;
|
||
|
int[][] sum = new int[xLength + 1][yLength + 1];
|
||
|
Map<Integer, Integer> map = new HashMap<>();
|
||
|
int count = 0;
|
||
|
for (int i = 1; i < xLength + 1; i++) {
|
||
|
for (int j = 1; j < yLength + 1; j++) {
|
||
|
sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];
|
||
|
if (matrix[i - 1][j - 1] == target) {
|
||
|
count++;
|
||
|
}
|
||
|
map.put(sum[i][j], map.getOrDefault(sum[i][j], 0));
|
||
|
}
|
||
|
}
|
||
|
for (int key : map.keySet()) {
|
||
|
int value = map.get(key);
|
||
|
if (key == 2 * target && value > 1) {
|
||
|
count += value * (value - 1) / 2;
|
||
|
} else if (key > target && map.containsKey(key - target)) {
|
||
|
count += value * map.get(key - target);
|
||
|
}
|
||
|
}
|
||
|
return count;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
//total_testcases:40
|
||
|
//total_correct:3
|
||
|
//input_formatted:[[1,-1],[-1,1]]
|
||
|
0
|
||
|
//expected_output:5
|
||
|
//code_output:0
|