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

leetcode1314

时间:2020-01-12 09:24:06      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:计算   Fix   min   ==   算法思路   prefix   block   矩阵   else   

 1 class Solution:
 2     def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:
 3         r,c = len(mat),len(mat[0])
 4         prefixsum = [[0 for _ in range(c)]for _ in range(r)]
 5         for i in range(r):
 6             prefixsum[i][0] = mat[i][0]
 7             for j in range(1,c):
 8                 prefixsum[i][j] = mat[i][j] + prefixsum[i][j-1]
 9         for j in range(c):
10             for i in range(1,r):
11                 prefixsum[i][j] = prefixsum[i-1][j] + prefixsum[i][j]
12         #print(prefixsum)
13         res = [[0 for _ in range(c)]for _ in range(r)]
14         for i in range(r):
15             for j in range(c):
16                 r_low,r_high = max(i - K,0),min(i + K,r-1)
17                 c_low,c_high = max(j - K,0),min(j + K,c-1)
18                 #print(r_low,c_low,r_high,c_high)
19                 
20                 if r_low >= 1 and c_low >= 1:
21                     res[i][j] = prefixsum[r_high][c_high] - prefixsum[r_low-1][c_high] - prefixsum[r_high][c_low-1] + prefixsum[r_low-1][c_low-1]
22                 elif r_low >= 1 and c_low == 0:
23                     res[i][j] = prefixsum[r_high][c_high] - prefixsum[r_low-1][c_high]
24                 elif r_low == 0 and c_low >= 1:
25                     res[i][j] = prefixsum[r_high][c_high] - prefixsum[r_high][c_low-1]
26                 else:
27                     res[i][j] = prefixsum[r_high][c_high]
28         return res

算法思路:二维矩阵求和。

先计算前序和,然后计算矩形子区域的和。共分4种情况讨论。

leetcode1314

标签:计算   Fix   min   ==   算法思路   prefix   block   矩阵   else   

原文地址:https://www.cnblogs.com/asenyang/p/12181599.html

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