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
| class Solution { public int[][] matrixBlockSum(int[][] mat, int K) { int n = mat.length; int c = mat[0].length; int[][] result = new int[n][c];
for (int i = 0; i < n; i++) { for (int j = 0; j < c; j++) { int xmin = i - K < 0 ? 0 : i - K; int xmax = i + K > n - 1 ? n - 1 : i + K; int ymin = j - K < 0 ? 0 : j - K; int ymax = j + K > c - 1 ? c - 1 : j + K; result[i][j] = caculate(mat, xmin, xmax, ymin, ymax); } } return result; }
public int caculate(int[][] mat, int xmin, int xmax, int ymin, int ymax) { int result = 0; for (int i = xmin; i <= xmax; i++) { for (int j = ymin; j <= ymax; j++) { result += mat[i][j]; } } return result; } }
|