#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;
}