-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathSubMatricesWithSumZero.cpp
77 lines (60 loc) · 1.11 KB
/
SubMatricesWithSumZero.cpp
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
Given a 2D matrix, find the number non-empty sub matrices, such that the sum of the elements inside the sub matrix is equal to 0. (note: elements might be negative).
Example:
Input
-8 5 7
3 7 -8
5 -8 9
Output
2
Explanation
-8 5 7
3 7 -8
5 -8 9
-8 5 7
3 7 -8
5 -8 9
LINK: https://www.interviewbit.com/problems/sub-matrices-with-sum-zero/
*/
int res;
void maxZero(int temp[], int n)
{
unordered_map<int,int> mp;
mp[0] = 1;
int sum = 0;
for(int i=0;i<n;i++)
{
sum += temp[i];
if(mp.find(sum) != mp.end())
{
res += mp[sum];
mp[sum]++;
}
else
{
mp[sum] = 1;
}
}
}
int Solution::solve(vector<vector<int> > &A)
{
res = 0;
int r = A.size();
if(r==0)
return res;
int c = A[0].size();
if(c==0)
return res;
int temp[r];
for(int i=0;i<c;i++)
{
memset(temp,0,sizeof(temp));
for(int j=i;j<c;j++)
{
for(int k=0;k<r;k++)
temp[k] += A[k][j];
maxZero(temp, r);
}
}
return res;
}