classSolution {
public:int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size(), res =0;
for (int top =0; top < m; ++top) {
vector<int> colSum(n);
for (int bottom = top; bottom < m; ++bottom) {
for (int c =0; c < n; ++c)
colSum[c] += matrix[bottom][c];
unordered_map<int,int> count{{0,1}};
int curr =0;
for (int v : colSum) {
curr += v;
res += count[curr - target];
count[curr]++;
}
}
}
return res;
}
};
classSolution {
publicintnumSubmatrixSumTarget(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length, res = 0;
for (int top = 0; top < m; ++top) {
int[] colSum =newint[n];
for (int bottom = top; bottom < m; ++bottom) {
for (int c = 0; c < n; ++c)
colSum[c]+= matrix[bottom][c];
Map<Integer, Integer> count =new HashMap<>();
count.put(0, 1);
int curr = 0;
for (int v : colSum) {
curr += v;
res += count.getOrDefault(curr - target, 0);
count.put(curr, count.getOrDefault(curr, 0) + 1);
}
}
}
return res;
}
}
classSolution {
funnumSubmatrixSumTarget(matrix: Array<IntArray>, target: Int): Int {
val m = matrix.size
val n = matrix[0].size
var res = 0for (top in0 until m) {
val colSum = IntArray(n)
for (bottom in top until m) {
for (c in0 until n) colSum[c] += matrix[bottom][c]
val count = mutableMapOf(0 to 1)
var curr = 0for (v in colSum) {
curr += v
res += count.getOrDefault(curr - target, 0)
count[curr] = count.getOrDefault(curr, 0) + 1 }
}
}
return res
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defnumSubmatrixSumTarget(self, matrix: list[list[int]], target: int) -> int:
m, n = len(matrix), len(matrix[0])
res =0for top in range(m):
colSum = [0] * n
for bottom in range(top, m):
for c in range(n):
colSum[c] += matrix[bottom][c]
count = {0: 1}
curr =0for v in colSum:
curr += v
res += count.get(curr - target, 0)
count[curr] = count.get(curr, 0) +1return res