Program to find out the number of submatrices from a matrix where the sum of elements is equal to a specific value in C++


Suppose we are given a matrix that contains integer values. We have to find out the submatrices from the matrix where the sum of elements of the matrices is equal to a given target sum value. We return the number of submatrices.

So, if the input is like

0010
0100
0101
1101

and target = 5, then the output will be 3.

The number of submatrices whose sum of elements is equal to 6 is 2.

To solve this, we will follow these steps −

  • n := size of mat
  • m := (if n is same as 0, then 0, otherwise size of mat[0])
  • if m > n, then −
    • Define one 2D array transpose of dimensions m x n
    • for initialize i := 0, when i < n, update (increase i by 1), do −
      • for initialize j := 0, when j < m, update (increase j by 1), do −
        • transpose[j, i] := mat[i, j]
    • return solve(transpose, sumTarget)
  • ans := 0
  • for initialize p := 0, when p < m, update (increase p by 1), do −
    • Define an array arr
    • for initialize q := p, when q < m, update (increase q by 1), do −
      • for initialize i := 0, when i < n, update (increase i by 1), do −
        • arr[i] := arr[i] + mat[i, q]
      • Define one map pcnt containing key-value pair {0, 1}
      • pref := 0
      • for initialize i := 0, when i < n, update (increase i by 1), do −
        • pref := pref + arr[i]
        • tmp := the position where(pref - sumTarget) is in pcnt
        • if tmp is not equal to end position of pcnt, then −
          • (increase pcnt[pref] by 1)
  • return ans

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>

using namespace std;

int solve(vector<vector<int>>& mat, int sumTarget) {
   int n = mat.size();
   int m = n == 0 ? 0 : mat[0].size();

   if (m > n) {
      vector<vector<int>> transpose(m, vector<int>(n));
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < m; j++) {
            transpose[j][i] = mat[i][j];
         }
      }
      return solve(transpose, sumTarget);
   }

   int ans = 0;
   for (int p = 0; p < m; p++) {
      vector<int> arr(n);
      for (int q = p; q < m; q++) {
         for (int i = 0; i < n; i++) {
            arr[i] += mat[i][q];
         }

         unordered_map<int, int> pcnt = {{0, 1}};
         int pref = 0;
         for (int i = 0; i < n; i++) {
            pref += arr[i];
            auto tmp = pcnt.find(pref - sumTarget);
            if (tmp != end(pcnt)) ans += tmp->second;
            pcnt[pref]++;
         }
      }
   }
   return ans;
}

int main() {
   vector<vector<int>> mat = {{0, 0, 1, 0}, {0, 1, 0, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}};
cout<< solve(mat, 5) <<endl;
return 0;
}

Input

{{0, 0, 1, 0}, {0, 1, 0, 0}, {0, 1, 0, 1}, {1, 1, 0, 1}}, 5

Output

3

Updated on: 16-Oct-2021

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements