[LeetCode] Matrix Block Sum

1314. Matrix Block Sum

Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:

  • i - k <= r <= i + k,
  • j - k <= c <= j + k, and
  • (r, c) is a valid position in the matrix.
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
class Solution {
int getOrZero(vector<vector<int>>& mat, int n, int m, int y, int x) {
if(0 <= x and x < m and 0 <= y and y < n)
return mat[y][x];
return 0;
}
public:
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
int n = mat.size(), m = mat[0].size();
vector<vector<int>> res(n,vector<int>(m));
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
mat[i][j] += getOrZero(mat,n,m,i-1,j) + getOrZero(mat,n,m,i,j-1) -getOrZero(mat,n,m,i-1,j-1);
}
}

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
res[i][j] = getOrZero(mat,n,m, min(i + k, n-1), min(j + k, m-1))
- getOrZero(mat,n,m,min(i+k,n-1),j-k-1)
- getOrZero(mat,n,m,i-k-1,min(j+k,m-1))
+ getOrZero(mat,n,m,i-k-1,j-k-1);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/14/PS/LeetCode/matrix-block-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.