diff --git a/cpp/number-of-submatrices-that-sum-to-target.cpp b/cpp/number-of-submatrices-that-sum-to-target.cpp new file mode 100644 index 0000000..8a94c03 --- /dev/null +++ b/cpp/number-of-submatrices-that-sum-to-target.cpp @@ -0,0 +1,55 @@ +#include +#include + +class Solution { + public: + auto numSubmatrixSumTarget(const std::vector> &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 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{904}, + }, + 0) == 0); + + return 0; +}