# Number of Submatrices That Sum to Target in C++

C++Server Side ProgrammingProgramming

Suppose we have a matrix, and a target value, we have to find the number of non-empty submatrices that sum is same as target. Here a submatrix [(x1, y1), (x2, y2)] is the set of all cells matrix[x][y] with x in range x1 and x2 and y in range y1 and y2. Two submatrices [(x1, y1), (x2, y2)] and [(x1', y1'), (x2', y2')] are different if they have some coordinate that is different: like, if x1 is not same as x1'.

So, if the input is like

 0 1 0 1 1 1 0 1 0

and target = 0, then the output will be 4, this is because four 1x1 submatrices that only contain 0.

To solve this, we will follow these steps −

• ans := 0

• col := number of columns

• row := number of rows

• for initialize i := 0, when i < row, update (increase i by 1), do −

• for initialize j := 1, when j < col, update (increase j by 1), do −

• matrix[i, j] := matrix[i, j] + matrix[i, j - 1]

• Define one map m

• for initialize i := 0, when i < col, update (increase i by 1), do −

• for initialize j := i, when j < col, update (increase j by 1), do −

• clear the map m

• m := 1

• sum := 0

• for initialize k := 0, when k < row, update (increase k by 1), do −

• current := matrix[k, j]

• if i - 1 >= 0, then −

• current := current - matrix[k, i - 1]

• sum := sum + current

• ans := ans + m[target - sum]

• increase m[-sum] by 1

• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numSubmatrixSumTarget(vector<vector<int>>& matrix, int
target) {
int ans = 0;
int col = matrix.size();
int row = matrix.size();
for(int i = 0; i < row; i++){
for(int j = 1; j < col; j++){
matrix[i][j] += matrix[i][j - 1];
}
}
unordered_map <int, int> m;
for(int i = 0; i < col; i++){
for(int j = i; j < col; j++){
m.clear();
m = 1;
int sum = 0;
for(int k = 0; k < row; k++){
int current = matrix[k][j];
if(i - 1 >= 0)current -= matrix[k][i - 1];
sum += current;
ans += m[target - sum];
m[-sum]++;
}
}
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{0,1,0},{1,1,1},{0,1,0}};
cout << (ob.numSubmatrixSumTarget(v, 0));
}

## Input

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

## Output

4