码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】1314. Matrix Block Sum

时间:2020-01-12 18:28:51      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:span   题目   for   color   etc   osi   style   else   block   

题目如下:

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
        

【leetcode】1314. Matrix Block Sum

标签:span   题目   for   color   etc   osi   style   else   block   

原文地址:https://www.cnblogs.com/seyjs/p/12183197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!