Matrix Block Sum LeetCode solution in Java

1
class Solution {
2
public int[][] matrixBlockSum(int[][] mat, int k) {
3
int m = mat.length, n = mat[0].length;
4
int[][] answer = new int[m][n];
5
for (int i = 0; i < m; i++) {
6
for (int j = 0; j < n; j++) {
7
int val = 0;
8
// take new variables to get starting index of mat[r][c]
9
int p = i - k, q = j - k;
10
// make sure p and q are atleast 0 (i.e. valid)
11
while (p < 0) p++;
12
while (q < 0) q++;
13
// traverse again in the matrix with starting at p,q and ending at i+k and j+k
14
// add conditions to make sure the indices dont cross the values of m and n
15
for (int x = p; x <= i + k && x < m; x++) {
16
for (int y = q; y <= j + k && y < n; y++) {
17
val += mat[x][y];
18
}
19
}
20
answer[i][j] = val;
21
}
22
}
23
return answer;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0