cpp: add «1074. Number of Submatrices That Sum to Target»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-28 20:12:44 +01:00
parent 2c3f0e2255
commit 3f7519022a
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,55 @@
#include <cassert>
#include <vector>
class Solution {
public:
auto numSubmatrixSumTarget(const std::vector<std::vector<int>> &matrix,
int target) -> int {
int rows = matrix.size();
int cols = matrix[0].size();
int count = 0;
for (int l = 0; l < cols; ++l) {
std::vector<int> sums(rows, 0);
for (int r = l; r < cols; ++r) {
for (int i = 0; i < rows; ++i) {
sums[i] += matrix[i][r];
}
for (int i = 0; i < rows; ++i) {
int sum = 0;
for (int j = i; j < rows; ++j) {
sum += sums[j];
if (sum == target) {
++count;
}
}
}
}
}
return count;
}
};
int main() {
Solution s;
assert(s.numSubmatrixSumTarget(std::vector{std::vector{0, 1, 0},
std::vector{1, 1, 1},
std::vector{0, 1, 0}},
0) == 4);
assert(s.numSubmatrixSumTarget(
std::vector{std::vector{1, -1}, std::vector{-1, 1}}, 0) == 5);
assert(s.numSubmatrixSumTarget(
std::vector<std::vector<int>>{
std::vector{904},
},
0) == 0);
return 0;
}