-
Notifications
You must be signed in to change notification settings - Fork 0
/
1074.number-of-submatrices-that-sum-to-target.cpp
47 lines (46 loc) · 1.28 KB
/
1074.number-of-submatrices-that-sum-to-target.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
/*
* @lc app=leetcode id=1074 lang=cpp
*
* [1074] Number of Submatrices That Sum to Target
*/
// @lc code=start
class Solution
{
public:
int numSubmatrixSumTarget(vector<vector<int>> &matrix, int target)
{
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> prefix(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
prefix[i][j] = prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1] + matrix[i - 1][j - 1];
}
}
int res = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
for (int k = 1; k <= m; k++)
{
for (int l = 1; l <= m; l++)
{
if (i <= j && k <= l)
{
int sum = prefix[j][l] - prefix[i - 1][l] - prefix[j][k - 1] + prefix[i - 1][k - 1];
if (sum == target)
{
res++;
}
}
}
}
}
}
return res;
}
};
// @lc code=end