-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1314. Matrix Block Sum.cpp
More file actions
52 lines (47 loc) · 1.67 KB
/
Copy path1314. Matrix Block Sum.cpp
File metadata and controls
52 lines (47 loc) · 1.67 KB
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
class Solution {
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int K) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> dp = mat;
vector<vector<int>> ans;
int bottom, right, top, left;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i > 0){
dp[i][j] += dp[i-1][j];
}
if(j > 0){
dp[i][j] += dp[i][j-1];
}
if(i > 0 && j > 0){
dp[i][j] -= dp[i-1][j-1];
}
cout << dp[i][j] << " ";
}
cout << endl;
}
ans = dp;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
bottom = min(i + K, m - 1);
right = min(j + K, n - 1);
top = max(i - K - 1, -1); //-1 means invalid
left = max(j - K - 1, -1); //-1 means invalid
ans[i][j] = dp[bottom][right];
if(top != -1){
ans[i][j] -= dp[top][right];
// cout << i << ", " << j << ":- " << dp[top][right] << endl;
}
if(left >= 0){
ans[i][j] -= dp[bottom][left];
// cout << i << ", " << j << ":- " << dp[bottom][left] << endl;
}
if(top >= 0 && left >= 0){
ans[i][j] += dp[top][left];
// cout << i << ", " << j << ":+ " << dp[top][left] << endl;
}
}
}
return ans;
}
};