Skip to content

1314. Matrix Block Sum 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 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
class Solution {
 public:
  vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
    const int m = mat.size();
    const int n = mat[0].size();
    vector<vector<int>> ans(m, vector<int>(n));
    vector<vector<int>> prefix(m + 1, vector<int>(n + 1));

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        prefix[i + 1][j + 1] =
            mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        const int r1 = max(0, i - k) + 1;
        const int c1 = max(0, j - k) + 1;
        const int r2 = min(m - 1, i + k) + 1;
        const int c2 = min(n - 1, j + k) + 1;
        ans[i][j] = prefix[r2][c2] - prefix[r2][c1 - 1] - prefix[r1 - 1][c2] +
                    prefix[r1 - 1][c1 - 1];
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int[][] matrixBlockSum(int[][] mat, int k) {
    final int m = mat.length;
    final int n = mat[0].length;
    int[][] ans = new int[m][n];
    int[][] prefix = new int[m + 1][n + 1];

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        prefix[i + 1][j + 1] = mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];

    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j) {
        final int r1 = Math.max(0, i - k) + 1;
        final int c1 = Math.max(0, j - k) + 1;
        final int r2 = Math.min(m - 1, i + k) + 1;
        final int c2 = Math.min(n - 1, j + k) + 1;
        ans[i][j] =
            prefix[r2][c2] - prefix[r2][c1 - 1] - prefix[r1 - 1][c2] + prefix[r1 - 1][c1 - 1];
      }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
  def matrixBlockSum(self, mat: list[list[int]], k: int) -> list[list[int]]:
    m = len(mat)
    n = len(mat[0])
    ans = [[0] * n for _ in range(m)]
    prefix = [[0] * (n + 1) for _ in range(m + 1)]

    for i in range(m):
      for j in range(n):
        prefix[i + 1][j + 1] = (mat[i][j] + prefix[i][j + 1] +
                                prefix[i + 1][j] - prefix[i][j])

    for i in range(m):
      for j in range(n):
        r1 = max(0, i - k) + 1
        c1 = max(0, j - k) + 1
        r2 = min(m - 1, i + k) + 1
        c2 = min(n - 1, j + k) + 1
        ans[i][j] = (prefix[r2][c2] - prefix[r2][c1 - 1] -
                     prefix[r1 - 1][c2] + prefix[r1 - 1][c1 - 1])

    return ans