当前位置:网站首页>leetcode:1314. Matrix area and [2D prefix and template]
leetcode:1314. Matrix area and [2D prefix and template]
2022-07-04 04:29:00 【White speed Dragon King's review】
analysis
2D prefix and template
dp One more row and one more column of records 0 Convenient unified formula
ac code
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
# Two dimensional prefixes and
m, n = len(mat), len(mat[0])
# row and col Add a full line 0
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[1][1] = mat[0][0]
for j in range(2, n + 1):
dp[1][j] = mat[0][j - 1] + dp[1][j - 1]
for i in range(2, m + 1):
dp[i][1] = mat[i - 1][0] + dp[i - 1][1]
for i in range(2, m + 1):
for j in range(2, n + 1):
#print(i, j)
dp[i][j] = mat[i - 1][j - 1] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1]
#print(dp)
res = [[0] * n for _ in range(m)]
for i in range(1, m + 1):
for j in range(1, n + 1):
left, right = max(i - k, 1), min(m, i + k)
up, down = max(j - k, 1), min(n, j + k)
res[i - 1][j - 1] = dp[right][down] + dp[left - 1][up - 1] - dp[left - 1][down] - dp[right][up - 1]
return res
summary
2D prefix and board
边栏推荐
猜你喜欢
Flink learning 7: application structure
UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x98 in position 1093: illegal multibyte sequence
tdk-lambda电源主要应用
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
2021 RSC | Drug–target affinity prediction using graph neural network and contact maps
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
I.MX6U-ALPHA开发板(C语言版本LED驱动实验)
R语言中如何查看已安装的R包
北漂程序员,月薪20K,一年攒15W,正常吗?
随机推荐
B. All Distinct
02 specific implementation of LS command
戳气球和布尔运算问题(巨难)
How to view installed r packages in R language
Emlog用户注册插件 价值80元
Flink learning 6: programming model
分布式CAP理论
新手找陪驾要注意什么
【微信小程序】好看的轮播图组件
5张图告诉你:同样是职场人,差距怎么这么大?
Virtual commodity account trading platform source code_ Support personal QR code collection
Katalon uses script to query list size
批处理初识
Flink learning 8: data consistency
软件测试是干什么的 发现缺陷错误,提高软件的质量
RHCSA 03 - 文件的基础权限
Small record of thinking
统计遗传学:第三章,群体遗传
Application scheme of Puyuan ds1000z series digital oscilloscope in communication principle experiment
Leetcode skimming: binary tree 07 (maximum depth of binary tree)