|
| 1 | +/** |
| 2 | + * 1314. Matrix Block Sum |
| 3 | + * https://leetcode.com/problems/matrix-block-sum/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] |
| 7 | + * is the sum of all elements mat[r][c] for: |
| 8 | + * - i - k <= r <= i + k, |
| 9 | + * - j - k <= c <= j + k, and |
| 10 | + * - (r, c) is a valid position in the matrix. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {number[][]} mat |
| 15 | + * @param {number} k |
| 16 | + * @return {number[][]} |
| 17 | + */ |
| 18 | +var matrixBlockSum = function(mat, k) { |
| 19 | + const rows = mat.length; |
| 20 | + const cols = mat[0].length; |
| 21 | + const prefixSums = new Array(rows + 1).fill().map(() => new Array(cols + 1).fill(0)); |
| 22 | + |
| 23 | + for (let i = 0; i < rows; i++) { |
| 24 | + for (let j = 0; j < cols; j++) { |
| 25 | + prefixSums[i + 1][j + 1] = prefixSums[i + 1][j] |
| 26 | + + prefixSums[i][j + 1] - prefixSums[i][j] + mat[i][j]; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + const result = new Array(rows).fill().map(() => new Array(cols).fill(0)); |
| 31 | + |
| 32 | + for (let i = 0; i < rows; i++) { |
| 33 | + for (let j = 0; j < cols; j++) { |
| 34 | + const top = Math.max(0, i - k); |
| 35 | + const bottom = Math.min(rows - 1, i + k); |
| 36 | + const left = Math.max(0, j - k); |
| 37 | + const right = Math.min(cols - 1, j + k); |
| 38 | + |
| 39 | + result[i][j] = prefixSums[bottom + 1][right + 1] |
| 40 | + - prefixSums[bottom + 1][left] - prefixSums[top][right + 1] + prefixSums[top][left]; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | +}; |
0 commit comments