Question : https://leetcode.com/problems/matrix-block-sum/
I am trying to solve it using 2D prefix sum where sum[i][j]
is the sum of all the elements to its left side including the element and it's row and column.
Code :
class Solution {
public:
int n, m;
int getSum(int i, int j, vector<vector<int>>& sum) {
if(i<0 || j<0) return 0;
if (i >= n) i = m - 1;
if (j >= n) j = m - 1;
return sum[i][j];
}
vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
n = mat.size();
m = mat[0].size();
vector<vector<int>> sum(n, vector<int>(m, 0)), res(n, vector<int>(m, 0));
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
sum[i][j] = mat[i][j] + getSum(i-1, j, sum) + getSum(i, j-1, sum) - getSum(i-1, j-1, sum);
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
res[i][j] = getSum(i+k, j+k, sum) - getSum(i-k-1, j+k, sum) - getSum(i+k, j-k-1, sum) + getSum(i-k-1, j-k-1, sum);
}
}
return res;
}
};