<p>Given a <code>m x n</code> matrix <code>mat</code> and an integer <code>k</code>, return <em>a matrix</em> <code>answer</code> <em>where each</em> <code>answer[i][j]</code> <em>is the sum of all elements</em> <code>mat[r][c]</code> <em>for</em>:</p>

<ul>
	<li><code>i - k &lt;= r &lt;= i + k,</code></li>
	<li><code>j - k &lt;= c &lt;= j + k</code>, and</li>
	<li><code>(r, c)</code> is a valid position in the matrix.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
<strong>Output:</strong> [[12,21,16],[27,45,33],[24,39,28]]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
<strong>Output:</strong> [[45,45,45],[45,45,45],[45,45,45]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>m ==&nbsp;mat.length</code></li>
	<li><code>n ==&nbsp;mat[i].length</code></li>
	<li><code>1 &lt;= m, n, k &lt;= 100</code></li>
	<li><code>1 &lt;= mat[i][j] &lt;= 100</code></li>
</ul>

class Solution:
    def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:

        m, n = len(mat), len(mat[0])
        numMatrix = NumMatrix(mat)

        res = [[0] * n for _ in range(m)]

        for i in range(m):
            for j in range(n):

                r1 = max(i - k, 0)
                c1 = max(j - k, 0)

                r2 = min(i + k, m - 1)
                c2 = min(j + k, n - 1)

                res[i][j] = numMatrix.sumRegion(r1, c1, r2, c2)
        return res




class NumMatrix:

    def __init__(self, matrix: List[List[int]]):

        self.presumMatrix = [[0] * (len(matrix[0]) + 1) for _ in range(len(matrix) + 1)]

        for i in range(1, len(self.presumMatrix)):
            for j in range(1, len(self.presumMatrix[0])):

                self.presumMatrix[i][j] = matrix[i - 1][j - 1] + self.presumMatrix[i - 1][j] + self.presumMatrix[i][j - 1] - self.presumMatrix[i - 1][j - 1]
        

    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:

        return self.presumMatrix[row2 + 1][col2 + 1] - self.presumMatrix[row1][col2 + 1] - self.presumMatrix[row2 + 1][col1] + self.presumMatrix[row1][col1]
        
18000