[InterviewBit] Sub Matrices with sum Zero

Sub Matrices with sum Zero

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int Solution::solve(vector<vector<int>> &A) {
int n = A.size(), m = A[0].size();
vector<vector<int>> psum(n,vector<int>(m,0));
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
psum[i][j] += A[i][j];
if(i) psum[i][j] += psum[i-1][j];
if(j) psum[i][j] += psum[i][j-1];
if(i and j) psum[i][j] -= psum[i-1][j-1];
}
}
int res = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int k = 0; k <= i; k++) {
for(int l = 0; l <= j; l++) {
int now = psum[i][j];
if(k) now -= psum[k-1][j];
if(l) now -= psum[i][l-1];
if(k and l) now += psum[k-1][l-1];
if(now == 0) res += 1;
}
}
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/18/PS/interviewbit/sub-matrices-with-sum-zero/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.