【leetcode】1314. Matrix Block Sum

题目如下:

Given a m * n matrix mat and an integer K, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for i - K <= r <= i + K, j - K <= c <= j + K, and (r, c) is a valid position in the matrix.

Example 1:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]

Example 2:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]], K = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n, K <= 100
  • 1 <= mat[i][j] <= 100

解题思路:记grid[i][j] 为 左上角顶点是(0,0),右下角顶点是(i,j) 的矩阵和,grid可以通过时间复杂度为O(n^2)的循环计算出来,接下来再遍历mat,计算出相应每个子矩阵和即可。

代码如下:

class Solution(object):
    def matrixBlockSum(self, mat, K):
        """
        :type mat: List[List[int]]
        :type K: int
        :rtype: List[List[int]]
        """
        res = [[0] * len(mat[0]) for _ in mat]
        grid = [[0] * len(mat[0]) for _ in mat]
        for i in range(len(mat)):
            count = 0
            for j in range(len(mat[0])):
                count += mat[i][j]
                grid[i][j] = count

        for i in range(len(res)):
            for j in range(len(res[i])):
                left = max(0,j-K)
                right = min(j+K,len(res[i])-1)
                count = 0
                for row in range(max(0,i-K),min(i+K+1,len(res))):
                    if left == 0:
                        count += grid[row][right]
                    else:
                        count += (grid[row][right] - grid[row][left-1])
                res[i][j] = count
        return res
        

猜你喜欢

转载自www.cnblogs.com/seyjs/p/12183197.html